repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
nosun/php-protobuf | tests/set_int_field.phpt | 421 | --TEST--
Protocol Buffers setting integer value
--SKIPIF--
<?php require 'skipif.inc' ?>
--FILE--
<?php
require 'test.inc';
$foo = new Foo();
/* from int type */
$foo->setInt32Field(2);
var_dump($foo->getInt32Field());
/* from float type */
$foo->setInt32Field(3.0);
var_dump($foo->getInt32Field());
/* from string type */
$foo->setInt32Field('4');
var_dump($foo->getInt32Field());
?>
--EXPECT--
int(2)
int(3)
int(4)
| bsd-3-clause |
stonier/ecto | include/ecto/python/std_map_indexing_suite.hpp | 17030 | // (C) Copyright Joel de Guzman 2003.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Modified by Troy D. Straszheim and Jakob van Santen, 2009-03-26
// Pulled in to ecto in 2010-11 by Troy D. Straszheim
// Willow Garage BSD License not applicable
#ifndef ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED
# define ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED
# include <ecto/python.hpp>
# include <boost/python/suite/indexing/indexing_suite.hpp>
# include <boost/python/iterator.hpp>
# include <boost/python/call_method.hpp>
# include <boost/python/tuple.hpp>
# include <boost/iterator/transform_iterator.hpp>
namespace bp = boost::python;
namespace boost { namespace python {
// Forward declaration
template <class Container, bool NoProxy, class DerivedPolicies>
class std_map_indexing_suite;
namespace detail
{
template <class Container, bool NoProxy>
class final_std_map_derived_policies
: public std_map_indexing_suite<Container,
NoProxy, final_std_map_derived_policies<Container, NoProxy> > {};
}
// The map_indexing_suite class is a predefined indexing_suite derived
// class for wrapping std::vector (and std::vector like) classes. It provides
// all the policies required by the indexing_suite (see indexing_suite).
// Example usage:
//
// class X {...};
//
// ...
//
// class_<std::map<std::string, X> >("XMap")
// .def(map_indexing_suite<std::map<std::string, X> >())
// ;
//
// By default indexed elements are returned by proxy. This can be
// disabled by supplying *true* in the NoProxy template parameter.
//
template <
class Container,
bool NoProxy = false,
class DerivedPolicies
= detail::final_std_map_derived_policies<Container, NoProxy> >
class std_map_indexing_suite
: public indexing_suite<
Container
, DerivedPolicies
, NoProxy
, true
, typename Container::value_type::second_type
, typename Container::key_type
, typename Container::key_type
>
{
public:
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
typedef typename Container::size_type size_type;
typedef typename Container::difference_type difference_type;
typedef typename Container::const_iterator const_iterator;
// __getitem__ for std::pair
// FIXME: horrible (20x) performance regression vs. (pair.key(),pair.data())
static object pair_getitem(value_type const& x, int i) {
if (i==0 || i==-2) return object(x.first);
else if (i==1 || i==-1) return object(x.second);
else {
PyErr_SetString(PyExc_IndexError,"Index out of range.");
throw_error_already_set();
return object(); // None
}
}
// __iter__ for std::pair
// here we cheat by making a tuple and returning its iterator
// FIXME: replace this with a pure C++ iterator
// how to handle the different return types of first and second?
static PyObject* pair_iter(value_type const& x) {
object tuple = bp::make_tuple(x.first,x.second);
return incref(tuple.attr("__iter__")().ptr());
}
// __len__ std::pair = 2
static int pair_len(value_type const& x) { return 2; }
// return a list of keys
static bp::list keys(Container const& x)
{
bp::list t;
for(typename Container::const_iterator it = x.begin(); it != x.end(); it++)
t.append(it->first);
return t;
}
// return a list of values
static bp::list values(Container const& x)
{
bp::list t;
for(typename Container::const_iterator it = x.begin(); it != x.end(); it++)
t.append(it->second);
return t;
}
// return a list of (key,value) tuples
static bp::list items(Container const& x)
{
bp::list t;
for(typename Container::const_iterator it = x.begin(); it != x.end(); it++)
t.append(bp::make_tuple(it->first, it->second));
return t;
}
#if 0
// return a shallow copy of the map
// FIXME: is this actually a shallow copy, or did i duplicate the pairs?
static Container copy(Container const& x)
{
Container newmap;
for(const_iterator it = x.begin();it != x.end();it++) newmap.insert(*it);
return newmap;
}
#endif
// get with default value
static object dict_get(Container const& x, index_type const& k, object const& default_val = object())
{
const_iterator it = x.find(k);
if (it != x.end()) return object(it->second);
else return default_val;
}
// preserve default value info
BOOST_PYTHON_FUNCTION_OVERLOADS(dict_get_overloads, dict_get, 2, 3);
// pop map[key], or throw an error if it doesn't exist
static object dict_pop(Container & x, index_type const& k)
{
const_iterator it = x.find(k);
object result;
if (it != x.end()) {
result = object(it->second);
x.erase(it->first);
return result;
}
else {
PyErr_SetString(PyExc_KeyError,"Key not found.");
throw_error_already_set();
return object(); // None
};
}
// pop map[key], or return default_val if it doesn't exist
static object dict_pop_default(Container & x, index_type const& k, object const& default_val)
{
const_iterator it = x.find(k);
object result;
if (it != x.end()) {
result = object(it->second);
x.erase(it->first);
return result;
}
else return default_val;
}
// pop a tuple, or throw an error if empty
static object dict_pop_item(Container & x)
{
const_iterator it = x.begin();
object result;
if (it != x.end()) {
result = boost::python::make_tuple(it->first,it->second);
x.erase(it->first);
return result;
}
else {
PyErr_SetString(PyExc_KeyError,"No more items to pop");
throw_error_already_set();
return object(); // None
};
}
// create a new map with given keys, initialialized to value
static object dict_fromkeys(object const& keys, object const& value)
{
object newmap = object(typename Container::storage_type());
int numkeys = extract<int>(keys.attr("__len__")());
for(int i=0;i<numkeys;i++) { // 'cuz python is more fun in C++...
newmap.attr("__setitem__")
(keys.attr("__getitem__")(i),value);
}
return newmap;
}
// spice up the constructors a bit
template <typename PyClassT>
struct init_factory {
typedef typename PyClassT::metadata::holder Holder;
typedef bp::objects::instance<Holder> instance_t;
// connect the PyObject to a wrapped C++ instance
// borrowed from boost/python/object/make_holder.hpp
static void make_holder(PyObject *p)
{
void* memory = Holder::allocate(p, offsetof(instance_t, storage), sizeof(Holder));
try {
// this only works for blank () constructors
(new (memory) Holder(p))->install(p);
}
catch(...) {
Holder::deallocate(p, memory);
throw;
}
}
static void from_dict(PyObject *p, bp::dict const& dict)
{
make_holder(p);
object newmap = object(bp::handle<>(borrowed(p)));
newmap.attr("update")(dict);
}
static void from_list(PyObject *p, bp::list const& list)
{
make_holder(p);
object newmap = object(bp::handle<>(borrowed(p)));
newmap.attr("update")(bp::dict(list));
}
};
// copy keys and values from dictlike object (anything with keys())
static void dict_update(object & x, object const& dictlike)
{
object key;
object keys = dictlike.attr("keys")();
int numkeys = extract<int>(keys.attr("__len__")());
for(int i=0;i<numkeys;i++) {
key = keys.attr("__getitem__")(i);
x.attr("__setitem__")(key,dictlike.attr("__getitem__")(key));
}
}
// set up operators to sample the key, value, or a tuple from a std::pair
struct iterkeys
{
typedef key_type result_type;
result_type operator()(value_type const& x) const
{
return x.first;
}
};
struct itervalues
{
typedef data_type result_type;
result_type operator()(value_type const& x) const
{
return x.second;
}
};
struct iteritems {
typedef tuple result_type;
result_type operator()(value_type const& x) const
{
return boost::python::make_tuple(x.first,x.second);
}
};
template <typename Transform>
struct make_transform_impl
{
typedef boost::transform_iterator<Transform, const_iterator> iterator;
static iterator begin(const Container& m)
{
return boost::make_transform_iterator(m.begin(), Transform());
}
static iterator end(const Container& m)
{
return boost::make_transform_iterator(m.end(), Transform());
}
static bp::object range()
{
return bp::range(&begin, &end);
}
};
template <typename Transform>
static bp::object
make_transform()
{
return make_transform_impl<Transform>::range();
}
static object
print_elem(typename Container::value_type const& e)
{
return "(%s, %s)" % python::make_tuple(e.first, e.second);
}
static
typename mpl::if_<
is_class<data_type>
, data_type&
, data_type
>::type
get_data(typename Container::value_type& e)
{
return e.second;
}
static typename Container::key_type
get_key(typename Container::value_type& e)
{
return e.first;
}
static data_type&
get_item(Container& container, index_type i_)
{
typename Container::iterator i = container.find(i_);
if (i == container.end())
{
PyErr_SetString(PyExc_KeyError, "Invalid key");
throw_error_already_set();
}
return i->second;
}
static void
set_item(Container& container, index_type i, data_type const& v)
{
container[i] = v;
}
static void
delete_item(Container& container, index_type i)
{
container.erase(i);
}
static size_t
size(Container& container)
{
return container.size();
}
static bool
contains(Container& container, key_type const& key)
{
return container.find(key) != container.end();
}
static bool
compare_index(Container& container, index_type a, index_type b)
{
return container.key_comp()(a, b);
}
static index_type
convert_index(Container& container, PyObject* i_)
{
extract<key_type const&> i(i_);
if (i.check())
{
return i();
}
else
{
extract<key_type> i(i_);
if (i.check())
return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
throw_error_already_set();
return index_type();
}
template <class Class>
static void
extension_def(Class& cl)
{
// Wrap the map's element (value_type)
std::string elem_name = "std_map_indexing_suite_";
std::string cl_name;
object class_name(cl.attr("__name__"));
extract<std::string> class_name_extractor(class_name);
cl_name = class_name_extractor();
elem_name += cl_name;
elem_name += "_entry";
typedef typename mpl::if_<
is_class<data_type>
, return_internal_reference<>
, default_call_policies
>::type get_data_return_policy;
class_<value_type>(elem_name.c_str())
.def("__repr__", &DerivedPolicies::print_elem)
.def("data", &DerivedPolicies::get_data, get_data_return_policy(),
"K.data() -> the value associated with this pair.\n")
.def("key", &DerivedPolicies::get_key,
"K.key() -> the key associated with this pair.\n")
.def("__getitem__",&pair_getitem)
.def("__iter__",&pair_iter)
.def("__len__",&pair_len)
.def("first",&DerivedPolicies::get_key,
"K.first() -> the first item in this pair.\n")
.def("second",&DerivedPolicies::get_data, get_data_return_policy(),
"K.second() -> the second item in this pair.\n")
;
// add convenience methods to the map
cl
// declare constructors in descending order of arity
.def("__init__", init_factory<Class>::from_list,
"Initialize with keys and values from a Python dictionary: {'key':'value'}\n")
.def("__init__", init_factory<Class>::from_dict,
"Initialize with keys and values as tuples in a Python list: [('key','value')]\n")
.def(init<>()) // restore default constructor
.def("keys", &keys, "D.keys() -> list of D's keys\n")
.def("has_key", &contains, "D.has_key(k) -> True if D has a key k, else False\n") // don't re-invent the wheel
.def("values", &values, "D.values() -> list of D's values\n")
.def("items", &items, "D.items() -> list of D's (key, value) pairs, as 2-tuples\n")
.def("clear", &Container::clear, "D.clear() -> None. Remove all items from D.\n")
//.def("copy", ©, "D.copy() -> a shallow copy of D\n")
.def("get", dict_get, dict_get_overloads(args("default_val"),
"D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.\n"))
.def("pop", &dict_pop )
.def("pop", &dict_pop_default,
"D.pop(k[,d]) -> v, remove specified key and return the corresponding value\nIf key is not found, d is returned if given, otherwise KeyError is raised\n")
.def("popitem", &dict_pop_item,
"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n2-tuple; but raise KeyError if D is empty\n")
.def("fromkeys", &dict_fromkeys,
(cl_name+".fromkeys(S,v) -> New "+cl_name+" with keys from S and values equal to v.\n").c_str())
.staticmethod("fromkeys")
.def("update", &dict_update,
"D.update(E) -> None. Update D from E: for k in E: D[k] = E[k]\n")
.def("iteritems",
make_transform<iteritems>(),
"D.iteritems() -> an iterator over the (key, value) items of D\n")
.def("iterkeys",
make_transform<iterkeys>(),
"D.iterkeys() -> an iterator over the keys of D\n")
.def("itervalues",
make_transform<itervalues>(),
"D.itervalues() -> an iterator over the values of D\n")
;
}
};
}} // namespace boost::python
#endif // ICETRAY_PYTHON_STD_MAP_INDEXING_SUITE_HPP_INCLUDED
| bsd-3-clause |
lxp/sulong | tests/sulong/c/truffle-c/bitFields/simpleStructTest4.c | 122 | struct test {
int val : 1;
};
int main() {
struct test t;
t.val = 1; // -1
long val = t.val;
return val + 1;
}
| bsd-3-clause |
chromium/chromium | components/autofill_assistant/android/java/src/org/chromium/components/autofill_assistant/user_data/AssistantLoginSection.java | 4011 | // Copyright 2019 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.
package org.chromium.components.autofill_assistant.user_data;
import static org.chromium.components.autofill_assistant.AssistantAccessibilityUtils.setAccessibility;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.chromium.components.autofill_assistant.R;
import org.chromium.components.autofill_assistant.user_data.AssistantCollectUserDataModel.LoginChoiceModel;
import java.util.List;
/**
* The login details section of the Autofill Assistant payment request.
*/
public class AssistantLoginSection extends AssistantCollectUserDataSection<LoginChoiceModel> {
AssistantLoginSection(Context context, ViewGroup parent) {
super(context, parent, R.layout.autofill_assistant_login, R.layout.autofill_assistant_login,
context.getResources().getDimensionPixelSize(
org.chromium.components.autofill_assistant.R.dimen
.autofill_assistant_payment_request_title_padding),
/*titleAddButton=*/null, /*listAddButton=*/null);
}
@Override
protected void createOrEditItem(@NonNull LoginChoiceModel oldItem) {
assert oldItem != null;
assert oldItem.mOption.getInfoPopup() != null;
oldItem.mOption.getInfoPopup().show(mContext);
}
@Override
protected void updateFullView(View fullView, LoginChoiceModel model) {
updateSummaryView(fullView, model);
}
@Override
protected void updateSummaryView(View summaryView, LoginChoiceModel model) {
AssistantLoginChoice option = model.mOption;
TextView labelView = summaryView.findViewById(R.id.label);
labelView.setText(option.getLabel());
TextView sublabelView = summaryView.findViewById(R.id.sublabel);
if (TextUtils.isEmpty(option.getSublabel())) {
sublabelView.setVisibility(View.GONE);
} else {
sublabelView.setText(option.getSublabel());
setAccessibility(sublabelView, option.getSublabelAccessibilityHint());
}
}
@Override
protected boolean canEditOption(LoginChoiceModel model) {
return model.mOption.getInfoPopup() != null;
}
@Override
protected @DrawableRes int getEditButtonDrawable(LoginChoiceModel model) {
return R.drawable.btn_info;
}
@Override
protected String getEditButtonContentDescription(LoginChoiceModel model) {
if (model.mOption.getEditButtonContentDescription() != null) {
return model.mOption.getEditButtonContentDescription();
} else {
return mContext.getString(R.string.learn_more);
}
}
@Override
protected boolean areEqual(
@Nullable LoginChoiceModel modelA, @Nullable LoginChoiceModel modelB) {
if (modelA == null || modelB == null) {
return modelA == modelB;
}
// Native ensures that each login choice has a unique identifier.
return TextUtils.equals(modelA.mOption.getIdentifier(), modelB.mOption.getIdentifier());
}
/**
* The login options have changed externally. This will rebuild the UI with the new/changed
* set of login options, while keeping the selected item if possible.
*/
void onLoginsChanged(List<LoginChoiceModel> options) {
int indexToSelect = -1;
if (mSelectedOption != null) {
for (int i = 0; i < getItems().size(); i++) {
if (areEqual(mSelectedOption, getItems().get(i))) {
indexToSelect = i;
break;
}
}
}
setItems(options, indexToSelect);
}
}
| bsd-3-clause |
iPlantCollaborativeOpenSource/irods-3.3.1-iplant | server/api/src/rsFileGetFsFreeSpace.c | 2855 | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* This is script-generated code (for the most part). */
/* See fileGetFsFreeSpace.h for a description of this API call.*/
#include "fileGetFsFreeSpace.h"
#include "miscServerFunct.h"
int
rsFileGetFsFreeSpace (rsComm_t *rsComm,
fileGetFsFreeSpaceInp_t *fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut_t **fileGetFsFreeSpaceOut)
{
rodsServerHost_t *rodsServerHost;
int remoteFlag;
int status;
*fileGetFsFreeSpaceOut = NULL;
remoteFlag = resolveHost (&fileGetFsFreeSpaceInp->addr, &rodsServerHost);
if (remoteFlag == LOCAL_HOST) {
status = _rsFileGetFsFreeSpace (rsComm, fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut);
} else if (remoteFlag == REMOTE_HOST) {
status = remoteFileGetFsFreeSpace (rsComm, fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut, rodsServerHost);
} else {
if (remoteFlag < 0) {
return (remoteFlag);
} else {
rodsLog (LOG_NOTICE,
"rsFileGetFsFreeSpace: resolveHost returned unrecognized value %d",
remoteFlag);
return (SYS_UNRECOGNIZED_REMOTE_FLAG);
}
}
/* Manually insert call-specific code here */
return (status);
}
int
remoteFileGetFsFreeSpace (rsComm_t *rsComm,
fileGetFsFreeSpaceInp_t *fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut_t **fileGetFsFreeSpaceOut,
rodsServerHost_t *rodsServerHost)
{
int status;
if (rodsServerHost == NULL) {
rodsLog (LOG_NOTICE,
"remoteFileGetFsFreeSpace: Invalid rodsServerHost");
return SYS_INVALID_SERVER_HOST;
}
if ((status = svrToSvrConnect (rsComm, rodsServerHost)) < 0) {
return status;
}
status = rcFileGetFsFreeSpace (rodsServerHost->conn, fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut);
if (status < 0) {
rodsLog (LOG_NOTICE,
"remoteFileGetFsFreeSpace: rcFileGetFsFreeSpace failed for %s, status = %d",
fileGetFsFreeSpaceInp->fileName, status);
}
return status;
}
int
_rsFileGetFsFreeSpace (rsComm_t *rsComm,
fileGetFsFreeSpaceInp_t *fileGetFsFreeSpaceInp,
fileGetFsFreeSpaceOut_t **fileGetFsFreeSpaceOut)
{
rodsLong_t status;
status = fileGetFsFreeSpace (fileGetFsFreeSpaceInp->fileType, rsComm,
fileGetFsFreeSpaceInp->fileName, fileGetFsFreeSpaceInp->flag);
if (status < 0) {
rodsLog (LOG_NOTICE,
"_rsFileGetFsFreeSpace: fileGetFsFreeSpace for %s, status = %lld",
fileGetFsFreeSpaceInp->fileName, status);
return ((int) status);
}
*fileGetFsFreeSpaceOut = (fileGetFsFreeSpaceOut_t*)malloc (sizeof (fileGetFsFreeSpaceOut_t));
(*fileGetFsFreeSpaceOut)->size = status;
return (0);
}
| bsd-3-clause |
oopos/go | src/cmd/godoc/template.go | 5495 | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Template support for writing HTML documents.
// Documents that include Template: true in their
// metadata are executed as input to text/template.
//
// This file defines functions for those templates to invoke.
// The template uses the function "code" to inject program
// source into the output by extracting code from files and
// injecting them as HTML-escaped <pre> blocks.
//
// The syntax is simple: 1, 2, or 3 space-separated arguments:
//
// Whole file:
// {{code "foo.go"}}
// One line (here the signature of main):
// {{code "foo.go" `/^func.main/`}}
// Block of text, determined by start and end (here the body of main):
// {{code "foo.go" `/^func.main/` `/^}/`
//
// Patterns can be `/regular expression/`, a decimal number, or "$"
// to signify the end of the file. In multi-line matches,
// lines that end with the four characters
// OMIT
// are omitted from the output, making it easy to provide marker
// lines in the input that will not appear in the output but are easy
// to identify by pattern.
package main
import (
"bytes"
"fmt"
"log"
"regexp"
"strings"
"text/template"
)
// Functions in this file panic on error, but the panic is recovered
// to an error by 'code'.
var templateFuncs = template.FuncMap{
"code": code,
}
// contents reads and returns the content of the named file
// (from the virtual file system, so for example /doc refers to $GOROOT/doc).
func contents(name string) string {
file, err := ReadFile(fs, name)
if err != nil {
log.Panic(err)
}
return string(file)
}
// format returns a textual representation of the arg, formatted according to its nature.
func format(arg interface{}) string {
switch arg := arg.(type) {
case int:
return fmt.Sprintf("%d", arg)
case string:
if len(arg) > 2 && arg[0] == '/' && arg[len(arg)-1] == '/' {
return fmt.Sprintf("%#q", arg)
}
return fmt.Sprintf("%q", arg)
default:
log.Panicf("unrecognized argument: %v type %T", arg, arg)
}
return ""
}
func code(file string, arg ...interface{}) (s string, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
text := contents(file)
var command string
switch len(arg) {
case 0:
// text is already whole file.
command = fmt.Sprintf("code %q", file)
case 1:
command = fmt.Sprintf("code %q %s", file, format(arg[0]))
text = oneLine(file, text, arg[0])
case 2:
command = fmt.Sprintf("code %q %s %s", file, format(arg[0]), format(arg[1]))
text = multipleLines(file, text, arg[0], arg[1])
default:
return "", fmt.Errorf("incorrect code invocation: code %q %q", file, arg)
}
// Trim spaces from output.
text = strings.Trim(text, "\n")
// Replace tabs by spaces, which work better in HTML.
text = strings.Replace(text, "\t", " ", -1)
var buf bytes.Buffer
// HTML-escape text and syntax-color comments like elsewhere.
FormatText(&buf, []byte(text), -1, true, "", nil)
// Include the command as a comment.
text = fmt.Sprintf("<pre><!--{{%s}}\n-->%s</pre>", command, buf.Bytes())
return text, nil
}
// parseArg returns the integer or string value of the argument and tells which it is.
func parseArg(arg interface{}, file string, max int) (ival int, sval string, isInt bool) {
switch n := arg.(type) {
case int:
if n <= 0 || n > max {
log.Panicf("%q:%d is out of range", file, n)
}
return n, "", true
case string:
return 0, n, false
}
log.Panicf("unrecognized argument %v type %T", arg, arg)
return
}
// oneLine returns the single line generated by a two-argument code invocation.
func oneLine(file, text string, arg interface{}) string {
lines := strings.SplitAfter(contents(file), "\n")
line, pattern, isInt := parseArg(arg, file, len(lines))
if isInt {
return lines[line-1]
}
return lines[match(file, 0, lines, pattern)-1]
}
// multipleLines returns the text generated by a three-argument code invocation.
func multipleLines(file, text string, arg1, arg2 interface{}) string {
lines := strings.SplitAfter(contents(file), "\n")
line1, pattern1, isInt1 := parseArg(arg1, file, len(lines))
line2, pattern2, isInt2 := parseArg(arg2, file, len(lines))
if !isInt1 {
line1 = match(file, 0, lines, pattern1)
}
if !isInt2 {
line2 = match(file, line1, lines, pattern2)
} else if line2 < line1 {
log.Panicf("lines out of order for %q: %d %d", text, line1, line2)
}
for k := line1 - 1; k < line2; k++ {
if strings.HasSuffix(lines[k], "OMIT\n") {
lines[k] = ""
}
}
return strings.Join(lines[line1-1:line2], "")
}
// match identifies the input line that matches the pattern in a code invocation.
// If start>0, match lines starting there rather than at the beginning.
// The return value is 1-indexed.
func match(file string, start int, lines []string, pattern string) int {
// $ matches the end of the file.
if pattern == "$" {
if len(lines) == 0 {
log.Panicf("%q: empty file", file)
}
return len(lines)
}
// /regexp/ matches the line that matches the regexp.
if len(pattern) > 2 && pattern[0] == '/' && pattern[len(pattern)-1] == '/' {
re, err := regexp.Compile(pattern[1 : len(pattern)-1])
if err != nil {
log.Panic(err)
}
for i := start; i < len(lines); i++ {
if re.MatchString(lines[i]) {
return i + 1
}
}
log.Panicf("%s: no match for %#q", file, pattern)
}
log.Panicf("unrecognized pattern: %q", pattern)
return 0
}
| bsd-3-clause |
ptosco/rdkit | Code/RDGeneral/types.h | 15891 | //
// Copyright 2001-2021 Greg Landrum and other RDKit contributors
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/export.h>
#ifndef RD_TYPES_H
#define RD_TYPES_H
#ifdef WIN32
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#define _DEFINED_USE_MATH_DEFINES
#endif
#endif
#include <cmath>
#ifdef _DEFINED_USE_MATH_DEFINES
#undef _DEFINED_USE_MATH_DEFINES
#undef _USE_MATH_DEFINES
#endif
#include "Invariant.h"
#include "Dict.h"
#include <vector>
#include <deque>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <numeric>
#include <list>
#include <limits>
#include <cstring>
#include <RDGeneral/BoostStartInclude.h>
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
#include <RDGeneral/BoostEndInclude.h>
namespace RDKit {
namespace detail {
// used in various places for computed properties
RDKIT_RDGENERAL_EXPORT extern const std::string computedPropName;
} // namespace detail
namespace common_properties {
///////////////////////////////////////////////////////////////
// Molecule Props
RDKIT_RDGENERAL_EXPORT extern const std::string _Name; // string
RDKIT_RDGENERAL_EXPORT extern const std::string MolFileInfo; // string
RDKIT_RDGENERAL_EXPORT extern const std::string MolFileComments; // string
RDKIT_RDGENERAL_EXPORT extern const std::string
_2DConf; // int (combine into dimension?)
RDKIT_RDGENERAL_EXPORT extern const std::string _3DConf; // int
RDKIT_RDGENERAL_EXPORT extern const std::string
_doIsoSmiles; // int (should probably be removed)
RDKIT_RDGENERAL_EXPORT extern const std::string extraRings; // vec<vec<int> >
RDKIT_RDGENERAL_EXPORT extern const std::string
_smilesAtomOutputOrder; // vec<int> computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_smilesBondOutputOrder; // vec<int> computed
RDKIT_RDGENERAL_EXPORT extern const std::string _StereochemDone; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _NeedsQueryScan; // int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string _fragSMARTS; // std::string
RDKIT_RDGENERAL_EXPORT extern const std::string
maxAttachIdx; // int TemplEnumTools.cpp
RDKIT_RDGENERAL_EXPORT extern const std::string origNoImplicit; // int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string
ringMembership; //? unused (molopstest.cpp)
// Computed Values
// ConnectivityDescriptors
RDKIT_RDGENERAL_EXPORT extern const std::string
_connectivityHKDeltas; // std::vector<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_connectivityNVals; // std::vector<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_crippenLogP; // double computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_crippenLogPContribs; // std::vector<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string _crippenMR; // double computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_crippenMRContribs; // std::vector<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string _labuteASA; // double computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_labuteAtomContribs; // vec<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_labuteAtomHContrib; // double computed
RDKIT_RDGENERAL_EXPORT extern const std::string _tpsa; // double computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_tpsaAtomContribs; // vec<double> computed
RDKIT_RDGENERAL_EXPORT extern const std::string
numArom; // int computed (only uses in tests?)
RDKIT_RDGENERAL_EXPORT extern const std::string
_MMFFSanitized; // int (bool) computed
RDKIT_RDGENERAL_EXPORT extern const std::string
_CrippenLogP; // Unused (in the basement)
RDKIT_RDGENERAL_EXPORT extern const std::string
_CrippenMR; // Unused (in the basement)
RDKIT_RDGENERAL_EXPORT extern const std::string
_GasteigerCharge; // used to hold partial charges
RDKIT_RDGENERAL_EXPORT extern const std::string
_GasteigerHCharge; // used to hold partial charges from implicit Hs
///////////////////////////////////////////////////////////////
// Atom Props
// Chirality stuff
RDKIT_RDGENERAL_EXPORT extern const std::string
_BondsPotentialStereo; // int (or bool) COMPUTED
RDKIT_RDGENERAL_EXPORT extern const std::string
_CIPCode; // std::string COMPUTED
RDKIT_RDGENERAL_EXPORT extern const std::string _CIPRank; // int COMPUTED
RDKIT_RDGENERAL_EXPORT extern const std::string _ChiralityPossible; // int
RDKIT_RDGENERAL_EXPORT extern const std::string
_UnknownStereo; // int (bool) AddHs/Chirality
RDKIT_RDGENERAL_EXPORT extern const std::string
_ringStereoAtoms; // int vect Canon/Chiral/MolHash/MolOps//Renumber//RWmol
RDKIT_RDGENERAL_EXPORT extern const std::string
_ringStereochemCand; // chirality bool COMPUTED
RDKIT_RDGENERAL_EXPORT extern const std::string
_ringStereoWarning; // obsolete ?
// Smiles parsing
RDKIT_RDGENERAL_EXPORT extern const std::string _SmilesStart; // int
RDKIT_RDGENERAL_EXPORT extern const std::string
_TraversalBondIndexOrder; // ? unused
RDKIT_RDGENERAL_EXPORT extern const std::string
_TraversalRingClosureBond; // unsigned int
RDKIT_RDGENERAL_EXPORT extern const std::string _TraversalStartPoint; // bool
RDKIT_RDGENERAL_EXPORT extern const std::string
_queryRootAtom; // int SLNParse/SubstructMatch
RDKIT_RDGENERAL_EXPORT extern const std::string _hasMassQuery; // atom bool
RDKIT_RDGENERAL_EXPORT extern const std::string _protected; // atom int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string
_supplementalSmilesLabel; // atom string (SmilesWrite)
RDKIT_RDGENERAL_EXPORT extern const std::string
_unspecifiedOrder; // atom int (bool) smarts/smiles
RDKIT_RDGENERAL_EXPORT extern const std::string
_RingClosures; // INT_VECT smarts/smiles/canon
RDKIT_RDGENERAL_EXPORT extern const std::string
atomLabel; // atom string from CXSMILES
// MDL Style Properties (MolFileParser)
RDKIT_RDGENERAL_EXPORT extern const std::string molAtomMapNumber; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molFileAlias; // string
RDKIT_RDGENERAL_EXPORT extern const std::string molFileValue; // string
RDKIT_RDGENERAL_EXPORT extern const std::string molInversionFlag; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molParity; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molStereoCare; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molRxnComponent; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molRxnRole; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molTotValence; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molSubstCount; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molAttachPoint; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molAttachOrder; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molAtomClass; // string
RDKIT_RDGENERAL_EXPORT extern const std::string molAtomSeqId; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molRxnExactChange; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molReactStatus; // int
RDKIT_RDGENERAL_EXPORT extern const std::string molFileLinkNodes; // string
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileRLabel; // unsigned int
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileChiralFlag; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileAtomQuery; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileBondQuery; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileBondEndPts; // string
RDKIT_RDGENERAL_EXPORT extern const std::string _MolFileBondAttach; // string
RDKIT_RDGENERAL_EXPORT extern const std::string
_MolFileBondType; // unsigned int
RDKIT_RDGENERAL_EXPORT extern const std::string
_MolFileBondStereo; // unsigned int
RDKIT_RDGENERAL_EXPORT extern const std::string
_MolFileBondCfg; // unsigned int
RDKIT_RDGENERAL_EXPORT extern const std::string
MRV_SMA; // smarts string from Marvin
RDKIT_RDGENERAL_EXPORT extern const std::string dummyLabel; // atom string
RDKIT_RDGENERAL_EXPORT extern const std::string
_QueryAtomGenericLabel; // string
// Reaction Information (Reactions.cpp)
RDKIT_RDGENERAL_EXPORT extern const std::string _QueryFormalCharge; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _QueryHCount; // int
RDKIT_RDGENERAL_EXPORT extern const std::string _QueryIsotope; // int
RDKIT_RDGENERAL_EXPORT extern const std::string
_QueryMass; // int = round(float * 1000)
RDKIT_RDGENERAL_EXPORT extern const std::string
_ReactionDegreeChanged; // int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string NullBond; // int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string _rgroupAtomMaps;
RDKIT_RDGENERAL_EXPORT extern const std::string _rgroupBonds;
RDKIT_RDGENERAL_EXPORT extern const std::string reactantAtomIdx;
RDKIT_RDGENERAL_EXPORT extern const std::string reactionMapNum;
// SLN
RDKIT_RDGENERAL_EXPORT extern const std::string
_AtomID; // unsigned int SLNParser
RDKIT_RDGENERAL_EXPORT extern const std::string
_starred; // atom int COMPUTED (SLN)
RDKIT_RDGENERAL_EXPORT extern const std::string
_SLN_s; // string SLNAttribs (chiral info)
RDKIT_RDGENERAL_EXPORT extern const std::string _Unfinished_SLN_; // int (bool)
// Smarts Smiles
RDKIT_RDGENERAL_EXPORT extern const std::string _brokenChirality; // atom bool
RDKIT_RDGENERAL_EXPORT extern const std::string isImplicit; // atom int (bool)
RDKIT_RDGENERAL_EXPORT extern const std::string
smilesSymbol; // atom string (only used in test?)
// Tripos
RDKIT_RDGENERAL_EXPORT extern const std::string
_TriposAtomType; // string Mol2FileParser
// missing defs for _TriposAtomName//_TriposPartialCharge...
// molecule drawing
RDKIT_RDGENERAL_EXPORT extern const std::string _displayLabel; // string
RDKIT_RDGENERAL_EXPORT extern const std::string _displayLabelW; // string
///////////////////////////////////////////////////////////////
// misc props
RDKIT_RDGENERAL_EXPORT extern const std::string
TWOD; // need THREED -> confusing using in TDTMol supplier
// converge with _2DConf?
RDKIT_RDGENERAL_EXPORT extern const std::string BalabanJ; // mol double
RDKIT_RDGENERAL_EXPORT extern const std::string BalanbanJ; // typo!! fix...
RDKIT_RDGENERAL_EXPORT extern const std::string Discrims; // FragCatalog Entry
// Subgraphs::DiscrimTuple (uint32,uint32,uint32)
RDKIT_RDGENERAL_EXPORT extern const std::string
DistanceMatrix_Paths; // boost::shared_array<double>
// - note, confusing creation of names in
// - getDistanceMat
RDKIT_RDGENERAL_EXPORT extern const std::string internalRgroupSmiles;
RDKIT_RDGENERAL_EXPORT extern const std::string molNote;
RDKIT_RDGENERAL_EXPORT extern const std::string atomNote;
RDKIT_RDGENERAL_EXPORT extern const std::string bondNote;
RDKIT_RDGENERAL_EXPORT extern const std::string _isotopicHs;
} // namespace common_properties
#ifndef WIN32
typedef long long int LONGINT;
#else
typedef __int64 LONGINT;
#endif
#ifdef max
#undef max // FUCK I hate this nonsense
#endif
#ifdef min
#undef min // FUCK I hate this nonsense
#endif
RDKIT_RDGENERAL_EXPORT extern const double MAX_DOUBLE;
RDKIT_RDGENERAL_EXPORT extern const double EPS_DOUBLE;
RDKIT_RDGENERAL_EXPORT extern const double SMALL_DOUBLE;
RDKIT_RDGENERAL_EXPORT extern const double MAX_INT;
RDKIT_RDGENERAL_EXPORT extern const double MAX_LONGINT;
typedef unsigned int UINT;
typedef unsigned short USHORT;
typedef unsigned char UCHAR;
typedef std::vector<int> INT_VECT;
typedef INT_VECT::iterator INT_VECT_I;
typedef INT_VECT::const_iterator INT_VECT_CI;
typedef INT_VECT::reverse_iterator INT_VECT_RI;
typedef INT_VECT::const_reverse_iterator INT_VECT_CRI;
typedef std::list<int> INT_LIST;
typedef INT_LIST::iterator INT_LIST_I;
typedef INT_LIST::const_iterator INT_LIST_CI;
typedef std::list<INT_VECT> LIST_INT_VECT;
typedef LIST_INT_VECT::iterator LIST_INT_VECT_I;
typedef LIST_INT_VECT::const_iterator LIST_INT_VECT_CI;
typedef std::vector<INT_VECT> VECT_INT_VECT;
typedef VECT_INT_VECT::iterator VECT_INT_VECT_I;
typedef VECT_INT_VECT::const_iterator VECT_INT_VECT_CI;
typedef std::vector<UINT>::const_iterator UINT_VECT_CI;
typedef std::vector<UINT> UINT_VECT;
typedef std::vector<std::string>::const_iterator STR_VECT_CI;
typedef std::vector<std::string>::iterator STR_VECT_I;
typedef std::vector<std::string> STR_VECT;
typedef std::vector<double> DOUBLE_VECT;
typedef DOUBLE_VECT::iterator DOUBLE_VECT_I;
typedef DOUBLE_VECT::const_iterator DOUBLE_VECT_CI;
typedef std::vector<DOUBLE_VECT> VECT_DOUBLE_VECT;
typedef VECT_DOUBLE_VECT::iterator VECT_DOUBLE_VECT_I;
typedef VECT_DOUBLE_VECT::const_iterator VECT_DOUBLE_VECT_CI;
typedef std::map<std::string, UINT> STR_UINT_MAP;
typedef std::map<std::string, UINT>::const_iterator STR_UINT_MAP_CI;
typedef std::map<int, INT_VECT> INT_INT_VECT_MAP;
typedef INT_INT_VECT_MAP::const_iterator INT_INT_VECT_MAP_CI;
typedef std::map<int, int> INT_MAP_INT;
typedef INT_MAP_INT::iterator INT_MAP_INT_I;
typedef INT_MAP_INT::const_iterator INT_MAP_INT_CI;
typedef std::deque<int> INT_DEQUE;
typedef INT_DEQUE::iterator INT_DEQUE_I;
typedef INT_DEQUE::const_iterator INT_DEQUE_CI;
typedef std::map<int, INT_DEQUE> INT_INT_DEQ_MAP;
typedef INT_INT_DEQ_MAP::const_iterator INT_INT_DEQ_MAP_CI;
typedef std::set<int> INT_SET;
typedef INT_SET::iterator INT_SET_I;
typedef INT_SET::const_iterator INT_SET_CI;
//! functor to compare two doubles with a tolerance
struct RDKIT_RDGENERAL_EXPORT ltDouble {
public:
ltDouble() {}
bool operator()(double d1, double d2) const {
if (fabs(d1 - d2) < _tol) {
return false;
} else {
return (d1 < d2);
}
}
private:
double _tol{1.0e-8};
};
//! std::map from double to integer.
typedef std::map<double, int, ltDouble> DOUBLE_INT_MAP;
//! functor for returning the larger of two values
template <typename T>
struct RDKIT_RDGENERAL_EXPORT larger_of {
T operator()(T arg1, T arg2) { return arg1 > arg2 ? arg1 : arg2; }
};
//! functor for comparing two strings
struct RDKIT_RDGENERAL_EXPORT charptr_functor {
bool operator()(const char *s1, const char *s2) const {
// std::cout << s1 << " " << s2 << " " << strcmp(s1, s2) << "\n";
return strcmp(s1, s2) < 0;
}
};
//! \brief calculate the union of two INT_VECTs and put the results in a
//! third vector
RDKIT_RDGENERAL_EXPORT void Union(const INT_VECT &r1, const INT_VECT &r2,
INT_VECT &res);
//! \brief calculate the intersection of two INT_VECTs and put the results in a
//! third vector
RDKIT_RDGENERAL_EXPORT void Intersect(const INT_VECT &r1, const INT_VECT &r2,
INT_VECT &res);
//! calculating the union of the INT_VECT's in a VECT_INT_VECT
/*!
\param rings the INT_VECT's to consider
\param res used to return results
\param exclude any values in this optional INT_VECT will be excluded
from the union.
*/
RDKIT_RDGENERAL_EXPORT void Union(const VECT_INT_VECT &rings, INT_VECT &res,
const INT_VECT *exclude = nullptr);
//! given a current combination of numbers change it to the next possible
// combination
/*!
\param comb the <b>sorted</b> vector to consider
\param tot the maximum number possible in the vector
\return -1 on failure, the index of the last number changed on success.
Example:
for all combinations 3 of numbers between 0 and tot=5
given (0,1,2) the function wil return (0,1,3) etc.
*/
RDKIT_RDGENERAL_EXPORT int nextCombination(INT_VECT &comb, int tot);
}; // namespace RDKit
#endif
| bsd-3-clause |
felixmulder/scala | test/disabled/scalacheck/HashTrieSplit.scala | 1021 |
import collection._
// checks whether hash tries split their iterators correctly
// even after some elements have been traversed
object Test {
def main(args: Array[String]) {
doesSplitOk
}
def doesSplitOk = {
val sz = 2000
var ht = new parallel.immutable.ParHashMap[Int, Int]
// println("creating trie")
for (i <- 0 until sz) ht += ((i + sz, i))
// println("created trie")
for (n <- 0 until (sz - 1)) {
// println("---------> n = " + n)
val pit = ht.parallelIterator
val pit2 = ht.parallelIterator
var i = 0
while (i < n) {
pit.next
pit2.next
i += 1
}
// println("splitting")
val pits = pit.split
val fst = pits(0).toSet
val snd = pits(1).toSet
val orig = pit2.toSet
if (orig.size != (fst.size + snd.size) || orig != (fst ++ snd)) {
println("Original: " + orig)
println("First: " + fst)
println("Second: " + snd)
assert(false)
}
}
}
}
| bsd-3-clause |
chromium/chromium | android_webview/java/src/org/chromium/android_webview/AwWebContentsDelegateAdapter.java | 14739 | // Copyright 2013 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.
package org.chromium.android_webview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.FrameLayout;
import org.chromium.android_webview.common.AwFeatures;
import org.chromium.base.Callback;
import org.chromium.base.ContentUriUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.task.AsyncTask;
import org.chromium.content_public.browser.InvalidateTypes;
import org.chromium.content_public.common.ContentUrlConstants;
import org.chromium.content_public.common.ResourceRequestBody;
import org.chromium.url.GURL;
/**
* Adapts the AwWebContentsDelegate interface to the AwContentsClient interface.
* This class also serves a secondary function of routing certain callbacks from the content layer
* to specific listener interfaces.
*/
class AwWebContentsDelegateAdapter extends AwWebContentsDelegate {
private static final String TAG = "AwWebContentsDelegateAdapter";
private final AwContents mAwContents;
private final AwContentsClient mContentsClient;
private final AwSettings mAwSettings;
private final Context mContext;
private View mContainerView;
private FrameLayout mCustomView;
private boolean mDidSynthesizePageLoad;
public AwWebContentsDelegateAdapter(AwContents awContents, AwContentsClient contentsClient,
AwSettings settings, Context context, View containerView) {
mAwContents = awContents;
mContentsClient = contentsClient;
mAwSettings = settings;
mContext = context;
mDidSynthesizePageLoad = false;
setContainerView(containerView);
}
public void setContainerView(View containerView) {
mContainerView = containerView;
mContainerView.setClickable(true);
}
@Override
public void handleKeyboardEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
int direction;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_DOWN:
direction = View.FOCUS_DOWN;
break;
case KeyEvent.KEYCODE_DPAD_UP:
direction = View.FOCUS_UP;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
direction = View.FOCUS_LEFT;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
direction = View.FOCUS_RIGHT;
break;
default:
direction = 0;
break;
}
if (direction != 0 && tryToMoveFocus(direction)) return;
}
handleMediaKey(event);
mContentsClient.onUnhandledKeyEvent(event);
}
/**
* Redispatches unhandled media keys. This allows bluetooth headphones with play/pause or
* other buttons to function correctly.
*/
private void handleMediaKey(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_HEADSETHOOK:
case KeyEvent.KEYCODE_MEDIA_PLAY:
case KeyEvent.KEYCODE_MEDIA_PAUSE:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_MEDIA_STOP:
case KeyEvent.KEYCODE_MEDIA_NEXT:
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
case KeyEvent.KEYCODE_MEDIA_REWIND:
case KeyEvent.KEYCODE_MEDIA_RECORD:
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
case KeyEvent.KEYCODE_MEDIA_CLOSE:
case KeyEvent.KEYCODE_MEDIA_EJECT:
case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
am.dispatchMediaKeyEvent(e);
break;
default:
break;
}
}
@Override
public boolean takeFocus(boolean reverse) {
int direction =
(reverse == (mContainerView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL))
? View.FOCUS_RIGHT : View.FOCUS_LEFT;
if (tryToMoveFocus(direction)) return true;
direction = reverse ? View.FOCUS_BACKWARD : View.FOCUS_FORWARD;
return tryToMoveFocus(direction);
}
private boolean tryToMoveFocus(int direction) {
View focus = mContainerView.focusSearch(direction);
return focus != null && focus != mContainerView && focus.requestFocus();
}
@Override
public boolean addMessageToConsole(int level, String message, int lineNumber,
String sourceId) {
@AwConsoleMessage.MessageLevel
int messageLevel = AwConsoleMessage.MESSAGE_LEVEL_DEBUG;
switch(level) {
case LOG_LEVEL_TIP:
messageLevel = AwConsoleMessage.MESSAGE_LEVEL_TIP;
break;
case LOG_LEVEL_LOG:
messageLevel = AwConsoleMessage.MESSAGE_LEVEL_LOG;
break;
case LOG_LEVEL_WARNING:
messageLevel = AwConsoleMessage.MESSAGE_LEVEL_WARNING;
break;
case LOG_LEVEL_ERROR:
messageLevel = AwConsoleMessage.MESSAGE_LEVEL_ERROR;
break;
default:
Log.w(TAG, "Unknown message level, defaulting to DEBUG");
break;
}
boolean result = mContentsClient.onConsoleMessage(
new AwConsoleMessage(message, sourceId, lineNumber, messageLevel));
return result;
}
@Override
public void onUpdateUrl(GURL url) {
// TODO: implement
}
@Override
public void openNewTab(GURL url, String extraHeaders, ResourceRequestBody postData,
int disposition, boolean isRendererInitiated) {
// This is only called in chrome layers.
assert false;
}
@Override
public void closeContents() {
mContentsClient.onCloseWindow();
}
@Override
@SuppressLint("HandlerLeak")
public void showRepostFormWarningDialog() {
// TODO(mkosiba) We should be using something akin to the JsResultReceiver as the
// callback parameter (instead of WebContents) and implement a way of converting
// that to a pair of messages.
final int msgContinuePendingReload = 1;
final int msgCancelPendingReload = 2;
// TODO(sgurun) Remember the URL to cancel the reload behavior
// if it is different than the most recent NavigationController entry.
final Handler handler = new Handler(ThreadUtils.getUiThreadLooper()) {
@Override
public void handleMessage(Message msg) {
if (mAwContents.getNavigationController() == null) return;
switch(msg.what) {
case msgContinuePendingReload: {
mAwContents.getNavigationController().continuePendingReload();
break;
}
case msgCancelPendingReload: {
mAwContents.getNavigationController().cancelPendingReload();
break;
}
default:
throw new IllegalStateException(
"WebContentsDelegateAdapter: unhandled message " + msg.what);
}
}
};
Message resend = handler.obtainMessage(msgContinuePendingReload);
Message dontResend = handler.obtainMessage(msgCancelPendingReload);
mContentsClient.getCallbackHelper().postOnFormResubmission(dontResend, resend);
}
@Override
public void runFileChooser(final int processId, final int renderId, final int modeFlags,
String acceptTypes, String title, String defaultFilename, boolean capture) {
int correctedModeFlags = FileModeConversionHelper.convertFileChooserMode(modeFlags);
AwContentsClient.FileChooserParamsImpl params = new AwContentsClient.FileChooserParamsImpl(
correctedModeFlags, acceptTypes, title, defaultFilename, capture);
mContentsClient.showFileChooser(new Callback<String[]>() {
boolean mCompleted;
@Override
public void onResult(String[] results) {
if (mCompleted) {
throw new IllegalStateException("Duplicate showFileChooser result");
}
mCompleted = true;
if (results == null) {
AwWebContentsDelegateJni.get().filesSelectedInChooser(
processId, renderId, correctedModeFlags, null, null);
return;
}
GetDisplayNameTask task = new GetDisplayNameTask(
mContext, processId, renderId, correctedModeFlags, results);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}, params);
}
@Override
public boolean addNewContents(boolean isDialog, boolean isUserGesture) {
return mContentsClient.onCreateWindow(isDialog, isUserGesture);
}
@Override
public void activateContents() {
mContentsClient.onRequestFocus();
}
@Override
public void navigationStateChanged(int flags) {
// If this is a popup whose document has been accessed by script, hint
// the client to show the last committed url through synthesizing a page
// load, as it may be unsafe to show the pending entry.
boolean shouldSynthesizePageLoad = ((flags & InvalidateTypes.URL) != 0)
&& mAwContents.isPopupWindow() && mAwContents.hasAccessedInitialDocument();
if (AwFeatureList.isEnabled(
AwFeatures.WEBVIEW_SYNTHESIZE_PAGE_LOAD_ONLY_ON_INITIAL_MAIN_DOCUMENT_ACCESS)) {
// Since we want to synthesize the page load only once for when the
// NavigationStateChange call is triggered by the first initial main
// document access, the flag must match InvalidateTypes.URL (the flag
// fired by NavigationControllerImpl::DidAccessInitialMainDocument())
// and we must check whether a page load has previously been
// synthesized here.
shouldSynthesizePageLoad &= (flags == InvalidateTypes.URL) && !mDidSynthesizePageLoad;
}
if (shouldSynthesizePageLoad) {
String url = mAwContents.getLastCommittedUrl();
url = TextUtils.isEmpty(url) ? ContentUrlConstants.ABOUT_BLANK_DISPLAY_URL : url;
mContentsClient.getCallbackHelper().postSynthesizedPageLoadingForUrlBarUpdate(url);
mDidSynthesizePageLoad = true;
}
}
@Override
public void enterFullscreenModeForTab(boolean prefersNavigationBar) {
enterFullscreen();
}
@Override
public void exitFullscreenModeForTab() {
exitFullscreen();
}
@Override
public int getDisplayMode() {
return mAwContents.getDisplayMode();
}
@Override
public void loadingStateChanged() {
mContentsClient.updateTitle(mAwContents.getTitle(), false);
}
/**
* Called to show the web contents in fullscreen mode.
*
* <p>If entering fullscreen on a video element the web contents will contain just
* the html5 video controls. {@link #enterFullscreenVideo(View)} will be called later
* once the ContentVideoView, which contains the hardware accelerated fullscreen video,
* is ready to be shown.
*/
private void enterFullscreen() {
if (mAwContents.isFullScreen()) {
return;
}
View fullscreenView = mAwContents.enterFullScreen();
if (fullscreenView == null) {
return;
}
AwContentsClient.CustomViewCallback cb = () -> {
if (mCustomView != null) {
mAwContents.requestExitFullscreen();
}
};
mCustomView = new FrameLayout(mContext);
mCustomView.addView(fullscreenView);
mContentsClient.onShowCustomView(mCustomView, cb);
}
/**
* Called to show the web contents in embedded mode.
*/
private void exitFullscreen() {
if (mCustomView != null) {
mCustomView = null;
mAwContents.exitFullScreen();
mContentsClient.onHideCustomView();
}
}
@Override
public boolean shouldBlockMediaRequest(GURL url) {
return mAwSettings != null
? mAwSettings.getBlockNetworkLoads() && URLUtil.isNetworkUrl(url.getSpec())
: true;
}
private static class GetDisplayNameTask extends AsyncTask<String[]> {
final int mProcessId;
final int mRenderId;
final int mModeFlags;
final String[] mFilePaths;
// The task doesn't run long, so we don't gain anything from a weak ref.
@SuppressLint("StaticFieldLeak")
final Context mContext;
public GetDisplayNameTask(
Context context, int processId, int renderId, int modeFlags, String[] filePaths) {
mProcessId = processId;
mRenderId = renderId;
mModeFlags = modeFlags;
mFilePaths = filePaths;
mContext = context;
}
@Override
protected String[] doInBackground() {
String[] displayNames = new String[mFilePaths.length];
for (int i = 0; i < mFilePaths.length; i++) {
displayNames[i] = resolveFileName(mFilePaths[i]);
}
return displayNames;
}
@Override
protected void onPostExecute(String[] result) {
AwWebContentsDelegateJni.get().filesSelectedInChooser(
mProcessId, mRenderId, mModeFlags, mFilePaths, result);
}
/**
* @return the display name of a path if it is a content URI and is present in the database
* or an empty string otherwise.
*/
private String resolveFileName(String filePath) {
if (filePath == null) return "";
Uri uri = Uri.parse(filePath);
return ContentUriUtils.getDisplayName(
uri, mContext, MediaStore.MediaColumns.DISPLAY_NAME);
}
}
}
| bsd-3-clause |
tectronics/afrimesh | dashboard/www/modules/utility.settings.potato.html | 12597 | <!--
* Afrimesh: easy management for B.A.T.M.A.N. wireless mesh networks
* Copyright (C) 2008-2009 Meraka Institute of the CSIR
* All rights reserved.
*
* This software is licensed as free software under the terms of the
* New BSD License. See /LICENSE for more information.
-->
<form class="two-column"
id="potato"
OnSubmit="return false;"
OnKeyPress="return disable_key(13, event);">
<table border="0">
<tr valign="top">
<td>
<fieldset id="network">
<legend>Network <button /></legend>
<div class="label">IP Address</div>
<input id="afrimesh|settings|network|wireless|address"/>
<div class="tooltip"><h3>ip address</h3></div>
<div class="label">Netmask</div>
<input id="afrimesh|settings|network|wireless|netmask" />
<div class="tooltip"><h3>netmask</h3></div>
</fieldset>
<fieldset id="network">
<legend>Wireless</legend>
<div class="label">Channel</div>
<input id="afrimesh|settings|network|wireless|channel" />
<div class="tooltip"><h3>channel</h3></div>
<div class="label">SSID</div>
<input id="afrimesh|settings|network|wireless|ssid" />
<div class="tooltip"><h3>ssid</h3></div>
<div class="label">BSSID</div>
<input id="afrimesh|settings|network|wireless|bssid" />
<div class="tooltip"><h3>bssid</h3></div>
</fieldset>
<fieldset id="map">
<legend>Map</legend>
<div class="label">Map Server</div>
<input id="afrimesh|settings|map|server" type="text" />
<div class="tooltip"><h3>map server</h3>
<p class="explain">The Network Map gets the terrain data from the server at this address.</p>
<p class="typical">If your mesh has internet access you will not need to change this setting.</p>
<p class="obstacle">
If your mesh does not have internet access you will need to set up your own map server and enter its address here.
</p>
<p class="learnmore">
You can learn how to set up your own map server by reading
<a href="http://code.google.com/p/afrimesh/wiki/HowTo">HowToMapServer</a>
</p>
</div>
</fieldset>
</td>
<td>
<fieldset id="batmand">
<legend>B.A.T.M.A.N. <button /></legend>
<div class="label">Vis Server</div>
<input id="afrimesh|settings|network|mesh|vis_server" style="background:#FFAAAA;" />
<div class="tooltip"><h3>visualization server</h3>
<p class="explain">The Network Map gets the available mesh nodes and their connections from the server at this address.</p>
<p class="typical">
By default the visualization server runs on the same address as the dashboard server and you should not need to change it.
</p>
<p class="learnmore">
You can learn how to configure a different vis server by reading the
<a href="http://code.google.com/p/afrimesh/wiki/HowTo">HowtoVisServer</a>
</p>
<p id="vis_server|error" style="color:#FF0000;"></p>
</div>
<div class="label">Gateway</div>
<input id="is_mesh_gateway" name="is_mesh_gateway" type="checkbox" />
<div class="routing_class">
<div class="label">Routing Class</div>
<select id="afrimesh|settings|network|mesh|routing_class">
<option value="0">disable default route</option>
<option value="1">use fastest connection</option>
<option value="2">use most stable connection</option>
<option value="3">auto</option>
</select>
<div class="tooltip"><h3>routing class</h3></div>
</div>
<div class="gateway_class">
<div class="label">Gateway Class</div>
<input id="afrimesh|settings|network|mesh|gateway_class" />
<div class="tooltip"><h3>gateway class</h3>
<p class="explain">
The gateway class is used to tell other nodes in the
network your available internet bandwidth. Enter any
number (optionally followed by "kbit" or "mbit") and
the daemon will guess your appropriate gateway
class. Use "/" to seperate the download and upload
rates. You can omit the upload rate and batmand will
assume an upload of download / 5.
</p>
<p class="typical">
default: <code>0 -> gateway disabled</code>
examples: <br/>
<code>5000<br/>
5000kbit<br/>
5mbit<br/>
5mbit/1024<br/>
5mbit/1024kbit<br/>
5mbit/1mbit<br/>
</code>
</p>
</div>
</div>
</fieldset>
<fieldset id="asterisk">
<legend>Telephony <button/></legend>
<!-- div class="label">Extension</div>
<input id="extension" />
<div class="tooltip"><h3>user extension</h3></div>
<div class="label">Inbound DID</div>
<input id="did|inbound" />
<div class="tooltip"><h3>inbound did</h3></div>
<div class="label">Trunk Calls</div>
<input id="afrimesh|settings|voip|iax|enable" type="checkbox" />
<div class="iax_trunk">
<div class="label">Asterisk Server</div>
<input id="afrimesh|settings|voip|iax|address" />
<div class="tooltip"><h3>asterisk</h3></div>
</div -->
<div class="label">SIP Trunk</div>
<input id="afrimesh|settings|voip|sip|enable" type="checkbox" />
<div class="sip_trunk">
<div class="label">Address</div>
<input id="afrimesh|settings|voip|sip|address" />
<div class="tooltip"><h3>sip address</h3></div>
<div class="label">Username</div>
<input id="afrimesh|settings|voip|sip|username" />
<div class="tooltip"><h3>sip username</h3></div>
<div class="label">Password</div>
<input type="password" id="afrimesh|settings|voip|sip|password" />
<div class="tooltip"><h3>sip password</h3></div>
</div>
</fieldset>
</td>
</tr>
</table>
<fieldset style="border:0px solid green; width:850px">
<div class="label">Location</div>
<div id="location" />
</fieldset>
</form>
<script type="text/javascript"> //<![CDATA[
(function() {
/** includes ------------------------------------------------------------ */
load("modules/utility.settings.js");
/** construction -------------------------------------------------------- */
ready = function() { // INJ 'ready' should be the only symbol we're exposing to the global namespace
console.debug("loaded utility.settings.html");
/** set controls to the values of afrimesh.settings.* ----------------- */
try {
populate_dom();
} catch (e) { console.error("populate_dom: " + e); }
/** install tooltips -------------------------------------------------- */
$("input.[id*=afrimesh]").tooltip({
position : ['bottom', 'right'], // place tooltip on the right edge
offset : [-20, 20], // a little tweaking of the position
effect : 'toggle', // use a simple show/hide effect
opacity : 0.8 // custom opacity setting
});
/** round corners ------------------------------------------------------ */
$(".tooltip").corner("tr 8px bl 8px br 8px");
/** style controls ----------------------------------------------------- */
$('form.two-column :checkbox').slider();
/** service reload buttons --------------------------------------------- */
$("form.two-column :button").hide();
function reload_service(fieldset) {
var button = $("fieldset#" + fieldset + " :button");
button.unbind("click");
button.click(function() {
$(this).html("<img src='images/reload-busy.gif'/>");
button.attr("disabled", true);
$("fieldset#" + fieldset + " *").attr("disabled", true);
var service = fieldset; // <-- any mapping required in future happens here
afrimesh.device.service.reload(afrimesh.settings.address, service, reload_complete);
function reload_complete(output) {
console.debug("Reloaded '" + fieldset + "'");
console.debug(output);
$("fieldset#" + fieldset + " *").attr("disabled", false);
$("fieldset#" + fieldset + " :button").hide();
update_sip_server(); // TODO - we should only call any associated update fn's
};
});
button.html("<img src='images/reload.png'/>");
$("fieldset#" + fieldset + " :button").show();
};
/** install callbacks to save settings --------------------------------- */
function save_element(id, value) {
if (Q(afrimesh, id) == value) {
return false;
}
console.debug("Saving setting: " + id + " -> " + value);
return afrimesh.settings.save(id, value);
};
$("input.[id*=afrimesh|settings]").bind("blur", function(event) {
if (save_element(this.id, this.value)) {
populate_dom();
reload_service($(this).closest("fieldset").attr("id"));
}
});
$("input.[id*=afrimesh|settings]").bind("keypress", function(event) {
if (event.keyCode != 13) return true;
if (save_element(this.id, this.value)) {
populate_dom();
}
return false;
});
$("select.[id*=afrimesh|settings]").bind("blur", function(event) {
if (save_element(this.id, this.value)) {
reload_service($(this).closest("fieldset").attr("id"));
}
});
$("input.[id*=afrimesh|settings|network|mesh|vis_server]").bind("blur", function(event) {
update_vis_server();
});
$("input.[id*=afrimesh|settings|map|server]").bind("blur", function(event) {
update_map_server();
});
$("#is_mesh_gateway").bind("change", function(event) {
if ($("input[name='is_mesh_gateway']").attr("checked")) {
$(".routing_class").hide();
$(".gateway_class").show();
$("select.[id*=afrimesh|settings|network|mesh|routing_class]").val(0);
save_element("afrimesh|settings|network|mesh|routing_class", "");
} else {
$(".routing_class").show();
$(".gateway_class").hide();
$("input.[id*=afrimesh|settings|network|mesh|gateway_class]").val("");
save_element("afrimesh|settings|network|mesh|gateway_class", "");
}
});
$("input.[id=afrimesh|settings|voip|iax|enable]").bind("change", function(event) {
if (save_element(this.id, this.checked.toString())) {
reload_service($(this).closest("fieldset").attr("id"));
}
update_iax_server();
});
$("input.[id=afrimesh|settings|voip|iax|address]").bind("blur", function(event) {
update_iax_server();
});
$("input.[id=afrimesh|settings|voip|sip|enable]").bind("change", function(event) {
if (save_element(this.id, this.checked.toString())) {
reload_service($(this).closest("fieldset").attr("id"));
update_sip_server();
}
});
$("fieldset#asterisk :text, :password").bind("blur", function(event) {
update_sip_server(); // TODO - only call if field has changed
});
/** update mesh routing controls --------------------------------- */
try {
update_mesh_controls();
} catch (e) { console.error("update_mesh_controls: " + e); }
/** query telephony servers for availability --------------------- */
update_sip_server();
update_iax_server();
/** query vis server for availability ---------------------------- */
update_vis_server();
/** query map server for availability ---------------------------- */
update_map_server();
return unload;
};
function unload() {
console.debug("unloaded utility.settings.html");
};
/** done ---------------------------------------------------------------- */
console.debug("loaded utility.settings.js");
})();
//]]></script>
| bsd-3-clause |
chromium/chromium | chrome/browser/download/download_shelf_context_menu.h | 4311 | // Copyright (c) 2011 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 CHROME_BROWSER_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_H_
#define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_H_
#include <memory>
#include <string>
#include "base/gtest_prod_util.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_commands.h"
#include "chrome/browser/download/download_ui_model.h"
#include "components/download/public/common/download_item.h"
#include "ui/base/models/simple_menu_model.h"
// This class is responsible for the download shelf context menu. Platform
// specific subclasses are responsible for creating and running the menu.
//
// The DownloadItem corresponding to the context menu is observed for removal or
// destruction.
class DownloadShelfContextMenu : public ui::SimpleMenuModel::Delegate,
public DownloadUIModel::Observer {
public:
// Only show a context menu for a dangerous download if it is malicious.
static bool WantsContextMenu(DownloadUIModel* download_model);
DownloadShelfContextMenu(const DownloadShelfContextMenu&) = delete;
DownloadShelfContextMenu& operator=(const DownloadShelfContextMenu&) = delete;
~DownloadShelfContextMenu() override;
protected:
explicit DownloadShelfContextMenu(base::WeakPtr<DownloadUIModel> download);
// Returns the correct menu model depending on the state of the download item.
// Returns nullptr if the download was destroyed.
ui::SimpleMenuModel* GetMenuModel();
// ui::SimpleMenuModel::Delegate:
bool IsCommandIdEnabled(int command_id) const override;
bool IsCommandIdChecked(int command_id) const override;
bool IsCommandIdVisible(int command_id) const override;
void ExecuteCommand(int command_id, int event_flags) override;
bool IsItemForCommandIdDynamic(int command_id) const override;
std::u16string GetLabelForCommandId(int command_id) const override;
private:
friend class DownloadShelfContextMenuTest;
FRIEND_TEST_ALL_PREFIXES(DownloadShelfContextMenuTest,
InvalidDownloadWontCrashContextMenu);
FRIEND_TEST_ALL_PREFIXES(DownloadShelfContextMenuTest, RecordCommandsEnabled);
// Detaches self from |download_item_|. Called when the DownloadItem is
// destroyed or when this object is being destroyed.
void DetachFromDownloadItem();
// DownloadUIModel::Observer overrides.
void OnDownloadDestroyed() override;
ui::SimpleMenuModel* GetInProgressMenuModel(bool is_download);
ui::SimpleMenuModel* GetInProgressPausedMenuModel(bool is_download);
ui::SimpleMenuModel* GetFinishedMenuModel(bool is_download);
ui::SimpleMenuModel* GetInterruptedMenuModel(bool is_download);
ui::SimpleMenuModel* GetMaybeMaliciousMenuModel(bool is_download);
ui::SimpleMenuModel* GetMaliciousMenuModel(bool is_download);
ui::SimpleMenuModel* GetDeepScanningMenuModel(bool is_download);
ui::SimpleMenuModel* GetMixedContentDownloadMenuModel();
void AddAutoOpenToMenu(ui::SimpleMenuModel* model);
void RecordCommandsEnabled(ui::SimpleMenuModel* model);
// We show slightly different menus if the download is in progress vs. if the
// download has finished.
std::unique_ptr<ui::SimpleMenuModel> in_progress_download_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> in_progress_download_paused_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> finished_download_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> interrupted_download_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> maybe_malicious_download_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> malicious_download_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> deep_scanning_menu_model_;
std::unique_ptr<ui::SimpleMenuModel> mixed_content_download_menu_model_;
// Whether or not a histogram has been emitted recording which
// Download commands were enabled
bool download_commands_enabled_recorded_ = false;
// Information source.
// Use WeakPtr because the context menu may outlive |download_|.
base::WeakPtr<DownloadUIModel> download_;
std::unique_ptr<DownloadCommands> download_commands_;
};
#endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_H_
| bsd-3-clause |
thcode/nico | tests/sdk.option.test.js | 1096 | require('should');
var option = require('..').sdk.option;
describe('option', function() {
it('can get default values', function() {
option.get('encoding').should.equal('utf8');
});
it('can set values', function() {
option.set('encoding', 'unicode');
option.get('encoding').should.equal('unicode');
option.clean();
option.get('encoding').should.equal('utf8');
option.option('encoding').should.equal('utf8');
option.option('encoding', 'unicode');
option.get('encoding').should.equal('unicode');
option.clean();
});
it('will init with some values', function() {
var o = new option.Option({foo: 'bar'});
o.get('foo').should.equal('bar');
});
it('can clean a key', function() {
var o = new option.Option({foo: 'bar'});
o.clean('foo');
o._cache.should.eql({});
});
it('can set defaults', function() {
option.defaults({
foo: {
foo: 'bar'
}
});
option.set('foo', {bar: 'foo'});
option.get('foo').should.have.ownProperty('foo');
option.get('foo').should.have.ownProperty('bar');
});
});
| bsd-3-clause |
shacker/django | django/views/generic/dates.py | 25251 | import datetime
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http import Http404
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.translation import gettext as _
from django.views.generic.base import View
from django.views.generic.detail import (
BaseDetailView, SingleObjectTemplateResponseMixin,
)
from django.views.generic.list import (
MultipleObjectMixin, MultipleObjectTemplateResponseMixin,
)
class YearMixin:
"""Mixin for views manipulating year-based data."""
year_format = '%Y'
year = None
def get_year_format(self):
"""
Get a year format string in strptime syntax to be used to parse the
year from url variables.
"""
return self.year_format
def get_year(self):
"""Return the year for which this view should display data."""
year = self.year
if year is None:
try:
year = self.kwargs['year']
except KeyError:
try:
year = self.request.GET['year']
except KeyError:
raise Http404(_("No year specified"))
return year
def get_next_year(self, date):
"""Get the next valid year."""
return _get_next_prev(self, date, is_previous=False, period='year')
def get_previous_year(self, date):
"""Get the previous valid year."""
return _get_next_prev(self, date, is_previous=True, period='year')
def _get_next_year(self, date):
"""
Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.
"""
try:
return date.replace(year=date.year + 1, month=1, day=1)
except ValueError:
raise Http404(_("Date out of range"))
def _get_current_year(self, date):
"""Return the start date of the current interval."""
return date.replace(month=1, day=1)
class MonthMixin:
"""Mixin for views manipulating month-based data."""
month_format = '%b'
month = None
def get_month_format(self):
"""
Get a month format string in strptime syntax to be used to parse the
month from url variables.
"""
return self.month_format
def get_month(self):
"""Return the month for which this view should display data."""
month = self.month
if month is None:
try:
month = self.kwargs['month']
except KeyError:
try:
month = self.request.GET['month']
except KeyError:
raise Http404(_("No month specified"))
return month
def get_next_month(self, date):
"""Get the next valid month."""
return _get_next_prev(self, date, is_previous=False, period='month')
def get_previous_month(self, date):
"""Get the previous valid month."""
return _get_next_prev(self, date, is_previous=True, period='month')
def _get_next_month(self, date):
"""
Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.
"""
if date.month == 12:
try:
return date.replace(year=date.year + 1, month=1, day=1)
except ValueError:
raise Http404(_("Date out of range"))
else:
return date.replace(month=date.month + 1, day=1)
def _get_current_month(self, date):
"""Return the start date of the previous interval."""
return date.replace(day=1)
class DayMixin:
"""Mixin for views manipulating day-based data."""
day_format = '%d'
day = None
def get_day_format(self):
"""
Get a day format string in strptime syntax to be used to parse the day
from url variables.
"""
return self.day_format
def get_day(self):
"""Return the day for which this view should display data."""
day = self.day
if day is None:
try:
day = self.kwargs['day']
except KeyError:
try:
day = self.request.GET['day']
except KeyError:
raise Http404(_("No day specified"))
return day
def get_next_day(self, date):
"""Get the next valid day."""
return _get_next_prev(self, date, is_previous=False, period='day')
def get_previous_day(self, date):
"""Get the previous valid day."""
return _get_next_prev(self, date, is_previous=True, period='day')
def _get_next_day(self, date):
"""
Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.
"""
return date + datetime.timedelta(days=1)
def _get_current_day(self, date):
"""Return the start date of the current interval."""
return date
class WeekMixin:
"""Mixin for views manipulating week-based data."""
week_format = '%U'
week = None
def get_week_format(self):
"""
Get a week format string in strptime syntax to be used to parse the
week from url variables.
"""
return self.week_format
def get_week(self):
"""Return the week for which this view should display data."""
week = self.week
if week is None:
try:
week = self.kwargs['week']
except KeyError:
try:
week = self.request.GET['week']
except KeyError:
raise Http404(_("No week specified"))
return week
def get_next_week(self, date):
"""Get the next valid week."""
return _get_next_prev(self, date, is_previous=False, period='week')
def get_previous_week(self, date):
"""Get the previous valid week."""
return _get_next_prev(self, date, is_previous=True, period='week')
def _get_next_week(self, date):
"""
Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.
"""
try:
return date + datetime.timedelta(days=7 - self._get_weekday(date))
except OverflowError:
raise Http404(_("Date out of range"))
def _get_current_week(self, date):
"""Return the start date of the current interval."""
return date - datetime.timedelta(self._get_weekday(date))
def _get_weekday(self, date):
"""
Return the weekday for a given date.
The first day according to the week format is 0 and the last day is 6.
"""
week_format = self.get_week_format()
if week_format == '%W': # week starts on Monday
return date.weekday()
elif week_format == '%U': # week starts on Sunday
return (date.weekday() + 1) % 7
else:
raise ValueError("unknown week format: %s" % week_format)
class DateMixin:
"""Mixin class for views manipulating date-based data."""
date_field = None
allow_future = False
def get_date_field(self):
"""Get the name of the date field to be used to filter by."""
if self.date_field is None:
raise ImproperlyConfigured("%s.date_field is required." % self.__class__.__name__)
return self.date_field
def get_allow_future(self):
"""
Return `True` if the view should be allowed to display objects from
the future.
"""
return self.allow_future
# Note: the following three methods only work in subclasses that also
# inherit SingleObjectMixin or MultipleObjectMixin.
@cached_property
def uses_datetime_field(self):
"""
Return `True` if the date field is a `DateTimeField` and `False`
if it's a `DateField`.
"""
model = self.get_queryset().model if self.model is None else self.model
field = model._meta.get_field(self.get_date_field())
return isinstance(field, models.DateTimeField)
def _make_date_lookup_arg(self, value):
"""
Convert a date into a datetime when the date field is a DateTimeField.
When time zone support is enabled, `date` is assumed to be in the
current time zone, so that displayed items are consistent with the URL.
"""
if self.uses_datetime_field:
value = datetime.datetime.combine(value, datetime.time.min)
if settings.USE_TZ:
value = timezone.make_aware(value, timezone.get_current_timezone())
return value
def _make_single_date_lookup(self, date):
"""
Get the lookup kwargs for filtering on a single date.
If the date field is a DateTimeField, we can't just filter on
date_field=date because that doesn't take the time into account.
"""
date_field = self.get_date_field()
if self.uses_datetime_field:
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(date + datetime.timedelta(days=1))
return {
'%s__gte' % date_field: since,
'%s__lt' % date_field: until,
}
else:
# Skip self._make_date_lookup_arg, it's a no-op in this branch.
return {date_field: date}
class BaseDateListView(MultipleObjectMixin, DateMixin, View):
"""Abstract base class for date-based views displaying a list of objects."""
allow_empty = False
date_list_period = 'year'
def get(self, request, *args, **kwargs):
self.date_list, self.object_list, extra_context = self.get_dated_items()
context = self.get_context_data(
object_list=self.object_list,
date_list=self.date_list,
**extra_context
)
return self.render_to_response(context)
def get_dated_items(self):
"""Obtain the list of dates and items."""
raise NotImplementedError('A DateView must provide an implementation of get_dated_items()')
def get_ordering(self):
"""
Return the field or fields to use for ordering the queryset; use the
date field by default.
"""
return '-%s' % self.get_date_field() if self.ordering is None else self.ordering
def get_dated_queryset(self, **lookup):
"""
Get a queryset properly filtered according to `allow_future` and any
extra lookup kwargs.
"""
qs = self.get_queryset().filter(**lookup)
date_field = self.get_date_field()
allow_future = self.get_allow_future()
allow_empty = self.get_allow_empty()
paginate_by = self.get_paginate_by(qs)
if not allow_future:
now = timezone.now() if self.uses_datetime_field else timezone_today()
qs = qs.filter(**{'%s__lte' % date_field: now})
if not allow_empty:
# When pagination is enabled, it's better to do a cheap query
# than to load the unpaginated queryset in memory.
is_empty = len(qs) == 0 if paginate_by is None else not qs.exists()
if is_empty:
raise Http404(_("No %(verbose_name_plural)s available") % {
'verbose_name_plural': qs.model._meta.verbose_name_plural,
})
return qs
def get_date_list_period(self):
"""
Get the aggregation period for the list of dates: 'year', 'month', or
'day'.
"""
return self.date_list_period
def get_date_list(self, queryset, date_type=None, ordering='ASC'):
"""
Get a date list by calling `queryset.dates/datetimes()`, checking
along the way for empty lists that aren't allowed.
"""
date_field = self.get_date_field()
allow_empty = self.get_allow_empty()
if date_type is None:
date_type = self.get_date_list_period()
if self.uses_datetime_field:
date_list = queryset.datetimes(date_field, date_type, ordering)
else:
date_list = queryset.dates(date_field, date_type, ordering)
if date_list is not None and not date_list and not allow_empty:
raise Http404(
_("No %(verbose_name_plural)s available") % {
'verbose_name_plural': queryset.model._meta.verbose_name_plural,
}
)
return date_list
class BaseArchiveIndexView(BaseDateListView):
"""
Base class for archives of date-based items. Requires a response mixin.
"""
context_object_name = 'latest'
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
qs = self.get_dated_queryset()
date_list = self.get_date_list(qs, ordering='DESC')
if not date_list:
qs = qs.none()
return (date_list, qs, {})
class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView):
"""Top-level archive of date-based items."""
template_name_suffix = '_archive'
class BaseYearArchiveView(YearMixin, BaseDateListView):
"""List of objects published in a given year."""
date_list_period = 'month'
make_object_list = False
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year = self.get_year()
date_field = self.get_date_field()
date = _date_from_string(year, self.get_year_format())
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_year(date))
lookup_kwargs = {
'%s__gte' % date_field: since,
'%s__lt' % date_field: until,
}
qs = self.get_dated_queryset(**lookup_kwargs)
date_list = self.get_date_list(qs)
if not self.get_make_object_list():
# We need this to be a queryset since parent classes introspect it
# to find information about the model.
qs = qs.none()
return (date_list, qs, {
'year': date,
'next_year': self.get_next_year(date),
'previous_year': self.get_previous_year(date),
})
def get_make_object_list(self):
"""
Return `True` if this view should contain the full list of objects in
the given year.
"""
return self.make_object_list
class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView):
"""List of objects published in a given year."""
template_name_suffix = '_archive_year'
class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView):
"""List of objects published in a given month."""
date_list_period = 'day'
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year = self.get_year()
month = self.get_month()
date_field = self.get_date_field()
date = _date_from_string(year, self.get_year_format(),
month, self.get_month_format())
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_month(date))
lookup_kwargs = {
'%s__gte' % date_field: since,
'%s__lt' % date_field: until,
}
qs = self.get_dated_queryset(**lookup_kwargs)
date_list = self.get_date_list(qs)
return (date_list, qs, {
'month': date,
'next_month': self.get_next_month(date),
'previous_month': self.get_previous_month(date),
})
class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView):
"""List of objects published in a given month."""
template_name_suffix = '_archive_month'
class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView):
"""List of objects published in a given week."""
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year = self.get_year()
week = self.get_week()
date_field = self.get_date_field()
week_format = self.get_week_format()
week_start = {
'%W': '1',
'%U': '0',
}[week_format]
date = _date_from_string(year, self.get_year_format(),
week_start, '%w',
week, week_format)
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_week(date))
lookup_kwargs = {
'%s__gte' % date_field: since,
'%s__lt' % date_field: until,
}
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {
'week': date,
'next_week': self.get_next_week(date),
'previous_week': self.get_previous_week(date),
})
class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView):
"""List of objects published in a given week."""
template_name_suffix = '_archive_week'
class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView):
"""List of objects published on a given day."""
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year = self.get_year()
month = self.get_month()
day = self.get_day()
date = _date_from_string(year, self.get_year_format(),
month, self.get_month_format(),
day, self.get_day_format())
return self._get_dated_items(date)
def _get_dated_items(self, date):
"""
Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial.
"""
lookup_kwargs = self._make_single_date_lookup(date)
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {
'day': date,
'previous_day': self.get_previous_day(date),
'next_day': self.get_next_day(date),
'previous_month': self.get_previous_month(date),
'next_month': self.get_next_month(date)
})
class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView):
"""List of objects published on a given day."""
template_name_suffix = "_archive_day"
class BaseTodayArchiveView(BaseDayArchiveView):
"""List of objects published today."""
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
return self._get_dated_items(datetime.date.today())
class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView):
"""List of objects published today."""
template_name_suffix = "_archive_day"
class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):
"""
Detail view of a single object on a single date; this differs from the
standard DetailView by accepting a year/month/day in the URL.
"""
def get_object(self, queryset=None):
"""Get the object this request displays."""
year = self.get_year()
month = self.get_month()
day = self.get_day()
date = _date_from_string(year, self.get_year_format(),
month, self.get_month_format(),
day, self.get_day_format())
# Use a custom queryset if provided
qs = self.get_queryset() if queryset is None else queryset
if not self.get_allow_future() and date > datetime.date.today():
raise Http404(_(
"Future %(verbose_name_plural)s not available because "
"%(class_name)s.allow_future is False."
) % {
'verbose_name_plural': qs.model._meta.verbose_name_plural,
'class_name': self.__class__.__name__,
})
# Filter down a queryset from self.queryset using the date from the
# URL. This'll get passed as the queryset to DetailView.get_object,
# which'll handle the 404
lookup_kwargs = self._make_single_date_lookup(date)
qs = qs.filter(**lookup_kwargs)
return super().get_object(queryset=qs)
class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView):
"""
Detail view of a single object on a single date; this differs from the
standard DetailView by accepting a year/month/day in the URL.
"""
template_name_suffix = '_detail'
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
"""
Get a datetime.date object given a format string and a year, month, and day
(only year is mandatory). Raise a 404 for an invalid date.
"""
format = year_format + delim + month_format + delim + day_format
datestr = str(year) + delim + str(month) + delim + str(day)
try:
return datetime.datetime.strptime(datestr, format).date()
except ValueError:
raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
'datestr': datestr,
'format': format,
})
def _get_next_prev(generic_view, date, is_previous, period):
"""
Get the next or the previous valid date. The idea is to allow links on
month/day views to never be 404s by never providing a date that'll be
invalid for the given view.
This is a bit complicated since it handles different intervals of time,
hence the coupling to generic_view.
However in essence the logic comes down to:
* If allow_empty and allow_future are both true, this is easy: just
return the naive result (just the next/previous day/week/month,
regardless of object existence.)
* If allow_empty is true, allow_future is false, and the naive result
isn't in the future, then return it; otherwise return None.
* If allow_empty is false and allow_future is true, return the next
date *that contains a valid object*, even if it's in the future. If
there are no next objects, return None.
* If allow_empty is false and allow_future is false, return the next
date that contains a valid object. If that date is in the future, or
if there are no next objects, return None.
"""
date_field = generic_view.get_date_field()
allow_empty = generic_view.get_allow_empty()
allow_future = generic_view.get_allow_future()
get_current = getattr(generic_view, '_get_current_%s' % period)
get_next = getattr(generic_view, '_get_next_%s' % period)
# Bounds of the current interval
start, end = get_current(date), get_next(date)
# If allow_empty is True, the naive result will be valid
if allow_empty:
if is_previous:
result = get_current(start - datetime.timedelta(days=1))
else:
result = end
if allow_future or result <= timezone_today():
return result
else:
return None
# Otherwise, we'll need to go to the database to look for an object
# whose date_field is at least (greater than/less than) the given
# naive result
else:
# Construct a lookup and an ordering depending on whether we're doing
# a previous date or a next date lookup.
if is_previous:
lookup = {'%s__lt' % date_field: generic_view._make_date_lookup_arg(start)}
ordering = '-%s' % date_field
else:
lookup = {'%s__gte' % date_field: generic_view._make_date_lookup_arg(end)}
ordering = date_field
# Filter out objects in the future if appropriate.
if not allow_future:
# Fortunately, to match the implementation of allow_future,
# we need __lte, which doesn't conflict with __lt above.
if generic_view.uses_datetime_field:
now = timezone.now()
else:
now = timezone_today()
lookup['%s__lte' % date_field] = now
qs = generic_view.get_queryset().filter(**lookup).order_by(ordering)
# Snag the first object from the queryset; if it doesn't exist that
# means there's no next/previous link available.
try:
result = getattr(qs[0], date_field)
except IndexError:
return None
# Convert datetimes to dates in the current time zone.
if generic_view.uses_datetime_field:
if settings.USE_TZ:
result = timezone.localtime(result)
result = result.date()
# Return the first day of the period.
return get_current(result)
def timezone_today():
"""Return the current date in the current time zone."""
if settings.USE_TZ:
return timezone.localdate()
else:
return datetime.date.today()
| bsd-3-clause |
hongliang5623/sentry | src/sentry/utils/raven.py | 3051 | from __future__ import absolute_import, print_function
import inspect
import logging
import raven
import sentry
from django.conf import settings
from django.db.utils import DatabaseError
from raven.contrib.django.client import DjangoClient
from . import metrics
UNSAFE_FILES = (
'sentry/event_manager.py',
'sentry/tasks/process_buffer.py',
)
def can_record_current_event():
"""
Tests the current stack for unsafe locations that would likely cause
recursion if an attempt to send to Sentry was made.
"""
for _, filename, _, _, _, _ in inspect.stack():
if filename.endswith(UNSAFE_FILES):
return False
return True
class SentryInternalClient(DjangoClient):
def is_enabled(self):
if getattr(settings, 'DISABLE_RAVEN', False):
return False
return settings.SENTRY_PROJECT is not None
def capture(self, *args, **kwargs):
if not can_record_current_event():
metrics.incr('internal.uncaptured.events')
self.error_logger.error('Not capturing event due to unsafe stacktrace:\n%r', kwargs)
return
return super(SentryInternalClient, self).capture(*args, **kwargs)
def send(self, **kwargs):
# TODO(dcramer): this should respect rate limits/etc and use the normal
# pipeline
from sentry.app import tsdb
from sentry.coreapi import ClientApiHelper
from sentry.event_manager import EventManager
from sentry.models import Project
helper = ClientApiHelper(
agent='raven-python/%s (sentry %s)' % (raven.VERSION, sentry.VERSION),
project_id=settings.SENTRY_PROJECT,
version=self.protocol_version,
)
try:
project = Project.objects.get_from_cache(id=settings.SENTRY_PROJECT)
except DatabaseError:
self.error_logger.error('Unable to fetch internal project',
exc_info=True)
except Project.DoesNotExist:
self.error_logger.error('Internal project (id=%s) does not exist',
settings.SENTRY_PROJECT)
return
helper.context.bind_project(project)
metrics.incr('events.total', 1)
kwargs['project'] = project.id
try:
manager = EventManager(kwargs)
data = manager.normalize()
tsdb.incr_multi([
(tsdb.models.project_total_received, project.id),
(tsdb.models.organization_total_received, project.organization_id),
])
helper.insert_data_to_database(data)
except Exception as e:
if self.raise_send_errors:
raise
self.error_logger.error(
'Unable to record event: %s\nEvent was: %r', e,
kwargs['message'], exc_info=True)
class SentryInternalFilter(logging.Filter):
def filter(self, record):
metrics.incr('internal.uncaptured.logs')
return can_record_current_event()
| bsd-3-clause |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/gcc/c-typeck.c | 266010 | /* Build expressions with type checking for C compiler.
Copyright (C) 1987, 1988, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
Free Software Foundation, Inc.
This file is part of GCC.
GCC 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, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* This file is part of the C front end.
It contains routines to build C expressions given their operands,
including computing the types of the result, C-specific error checks,
and some optimization. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "tree.h"
#include "langhooks.h"
#include "c-tree.h"
#include "tm_p.h"
#include "flags.h"
#include "output.h"
#include "expr.h"
#include "toplev.h"
#include "intl.h"
#include "ggc.h"
#include "target.h"
#include "tree-iterator.h"
#include "tree-gimple.h"
#include "tree-flow.h"
/* Possible cases of implicit bad conversions. Used to select
diagnostic messages in convert_for_assignment. */
enum impl_conv {
ic_argpass,
ic_argpass_nonproto,
ic_assign,
ic_init,
ic_return
};
/* The level of nesting inside "__alignof__". */
int in_alignof;
/* The level of nesting inside "sizeof". */
int in_sizeof;
/* The level of nesting inside "typeof". */
int in_typeof;
struct c_label_context_se *label_context_stack_se;
struct c_label_context_vm *label_context_stack_vm;
/* Nonzero if we've already printed a "missing braces around initializer"
message within this initializer. */
static int missing_braces_mentioned;
static int require_constant_value;
static int require_constant_elements;
static bool null_pointer_constant_p (tree);
static tree qualify_type (tree, tree);
static int tagged_types_tu_compatible_p (tree, tree);
static int comp_target_types (tree, tree);
static int function_types_compatible_p (tree, tree);
static int type_lists_compatible_p (tree, tree);
static tree decl_constant_value_for_broken_optimization (tree);
static tree lookup_field (tree, tree);
static tree convert_arguments (tree, tree, tree, tree);
static tree pointer_diff (tree, tree);
static tree convert_for_assignment (tree, tree, enum impl_conv, tree, tree,
int);
static tree valid_compound_expr_initializer (tree, tree);
static void push_string (const char *);
static void push_member_name (tree);
static int spelling_length (void);
static char *print_spelling (char *);
static void warning_init (const char *);
static tree digest_init (tree, tree, bool, int);
static void output_init_element (tree, bool, tree, tree, int);
static void output_pending_init_elements (int);
static int set_designator (int);
static void push_range_stack (tree);
static void add_pending_init (tree, tree);
static void set_nonincremental_init (void);
static void set_nonincremental_init_from_string (tree);
static tree find_init_member (tree);
static void readonly_error (tree, enum lvalue_use);
static int lvalue_or_else (tree, enum lvalue_use);
static int lvalue_p (tree);
static void record_maybe_used_decl (tree);
static int comptypes_internal (tree, tree);
/* Return true if EXP is a null pointer constant, false otherwise. */
static bool
null_pointer_constant_p (tree expr)
{
/* This should really operate on c_expr structures, but they aren't
yet available everywhere required. */
tree type = TREE_TYPE (expr);
return (TREE_CODE (expr) == INTEGER_CST
&& !TREE_CONSTANT_OVERFLOW (expr)
&& integer_zerop (expr)
&& (INTEGRAL_TYPE_P (type)
|| (TREE_CODE (type) == POINTER_TYPE
&& VOID_TYPE_P (TREE_TYPE (type))
&& TYPE_QUALS (TREE_TYPE (type)) == TYPE_UNQUALIFIED)));
}
/* This is a cache to hold if two types are compatible or not. */
struct tagged_tu_seen_cache {
const struct tagged_tu_seen_cache * next;
tree t1;
tree t2;
/* The return value of tagged_types_tu_compatible_p if we had seen
these two types already. */
int val;
};
static const struct tagged_tu_seen_cache * tagged_tu_seen_base;
static void free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *);
/* Do `exp = require_complete_type (exp);' to make sure exp
does not have an incomplete type. (That includes void types.) */
tree
require_complete_type (tree value)
{
tree type = TREE_TYPE (value);
if (value == error_mark_node || type == error_mark_node)
return error_mark_node;
/* First, detect a valid value with a complete type. */
if (COMPLETE_TYPE_P (type))
return value;
c_incomplete_type_error (value, type);
return error_mark_node;
}
/* Print an error message for invalid use of an incomplete type.
VALUE is the expression that was used (or 0 if that isn't known)
and TYPE is the type that was invalid. */
void
c_incomplete_type_error (tree value, tree type)
{
const char *type_code_string;
/* Avoid duplicate error message. */
if (TREE_CODE (type) == ERROR_MARK)
return;
if (value != 0 && (TREE_CODE (value) == VAR_DECL
|| TREE_CODE (value) == PARM_DECL))
error ("%qD has an incomplete type", value);
else
{
retry:
/* We must print an error message. Be clever about what it says. */
switch (TREE_CODE (type))
{
case RECORD_TYPE:
type_code_string = "struct";
break;
case UNION_TYPE:
type_code_string = "union";
break;
case ENUMERAL_TYPE:
type_code_string = "enum";
break;
case VOID_TYPE:
error ("invalid use of void expression");
return;
case ARRAY_TYPE:
if (TYPE_DOMAIN (type))
{
if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL)
{
error ("invalid use of flexible array member");
return;
}
type = TREE_TYPE (type);
goto retry;
}
error ("invalid use of array with unspecified bounds");
return;
default:
gcc_unreachable ();
}
if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE)
error ("invalid use of undefined type %<%s %E%>",
type_code_string, TYPE_NAME (type));
else
/* If this type has a typedef-name, the TYPE_NAME is a TYPE_DECL. */
error ("invalid use of incomplete typedef %qD", TYPE_NAME (type));
}
}
/* Given a type, apply default promotions wrt unnamed function
arguments and return the new type. */
tree
c_type_promotes_to (tree type)
{
if (TYPE_MAIN_VARIANT (type) == float_type_node)
return double_type_node;
if (c_promoting_integer_type_p (type))
{
/* Preserve unsignedness if not really getting any wider. */
if (TYPE_UNSIGNED (type)
&& (TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node)))
return unsigned_type_node;
return integer_type_node;
}
return type;
}
/* Return a variant of TYPE which has all the type qualifiers of LIKE
as well as those of TYPE. */
static tree
qualify_type (tree type, tree like)
{
return c_build_qualified_type (type,
TYPE_QUALS (type) | TYPE_QUALS (like));
}
/* Return true iff the given tree T is a variable length array. */
bool
c_vla_type_p (tree t)
{
if (TREE_CODE (t) == ARRAY_TYPE
&& C_TYPE_VARIABLE_SIZE (t))
return true;
return false;
}
/* Return the composite type of two compatible types.
We assume that comptypes has already been done and returned
nonzero; if that isn't so, this may crash. In particular, we
assume that qualifiers match. */
tree
composite_type (tree t1, tree t2)
{
enum tree_code code1;
enum tree_code code2;
tree attributes;
/* Save time if the two types are the same. */
if (t1 == t2) return t1;
/* If one type is nonsense, use the other. */
if (t1 == error_mark_node)
return t2;
if (t2 == error_mark_node)
return t1;
code1 = TREE_CODE (t1);
code2 = TREE_CODE (t2);
/* Merge the attributes. */
attributes = targetm.merge_type_attributes (t1, t2);
/* If one is an enumerated type and the other is the compatible
integer type, the composite type might be either of the two
(DR#013 question 3). For consistency, use the enumerated type as
the composite type. */
if (code1 == ENUMERAL_TYPE && code2 == INTEGER_TYPE)
return t1;
if (code2 == ENUMERAL_TYPE && code1 == INTEGER_TYPE)
return t2;
gcc_assert (code1 == code2);
switch (code1)
{
case POINTER_TYPE:
/* For two pointers, do this recursively on the target type. */
{
tree pointed_to_1 = TREE_TYPE (t1);
tree pointed_to_2 = TREE_TYPE (t2);
tree target = composite_type (pointed_to_1, pointed_to_2);
t1 = build_pointer_type (target);
t1 = build_type_attribute_variant (t1, attributes);
return qualify_type (t1, t2);
}
case ARRAY_TYPE:
{
tree elt = composite_type (TREE_TYPE (t1), TREE_TYPE (t2));
int quals;
tree unqual_elt;
tree d1 = TYPE_DOMAIN (t1);
tree d2 = TYPE_DOMAIN (t2);
bool d1_variable, d2_variable;
bool d1_zero, d2_zero;
/* We should not have any type quals on arrays at all. */
gcc_assert (!TYPE_QUALS (t1) && !TYPE_QUALS (t2));
d1_zero = d1 == 0 || !TYPE_MAX_VALUE (d1);
d2_zero = d2 == 0 || !TYPE_MAX_VALUE (d2);
d1_variable = (!d1_zero
&& (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST
|| TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST));
d2_variable = (!d2_zero
&& (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST
|| TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST));
d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1));
d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2));
/* Save space: see if the result is identical to one of the args. */
if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1)
&& (d2_variable || d2_zero || !d1_variable))
return build_type_attribute_variant (t1, attributes);
if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2)
&& (d1_variable || d1_zero || !d2_variable))
return build_type_attribute_variant (t2, attributes);
if (elt == TREE_TYPE (t1) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1))
return build_type_attribute_variant (t1, attributes);
if (elt == TREE_TYPE (t2) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1))
return build_type_attribute_variant (t2, attributes);
/* Merge the element types, and have a size if either arg has
one. We may have qualifiers on the element types. To set
up TYPE_MAIN_VARIANT correctly, we need to form the
composite of the unqualified types and add the qualifiers
back at the end. */
quals = TYPE_QUALS (strip_array_types (elt));
unqual_elt = c_build_qualified_type (elt, TYPE_UNQUALIFIED);
t1 = build_array_type (unqual_elt,
TYPE_DOMAIN ((TYPE_DOMAIN (t1)
&& (d2_variable
|| d2_zero
|| !d1_variable))
? t1
: t2));
t1 = c_build_qualified_type (t1, quals);
return build_type_attribute_variant (t1, attributes);
}
case ENUMERAL_TYPE:
case RECORD_TYPE:
case UNION_TYPE:
if (attributes != NULL)
{
/* Try harder not to create a new aggregate type. */
if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes))
return t1;
if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes))
return t2;
}
return build_type_attribute_variant (t1, attributes);
case FUNCTION_TYPE:
/* Function types: prefer the one that specified arg types.
If both do, merge the arg types. Also merge the return types. */
{
tree valtype = composite_type (TREE_TYPE (t1), TREE_TYPE (t2));
tree p1 = TYPE_ARG_TYPES (t1);
tree p2 = TYPE_ARG_TYPES (t2);
int len;
tree newargs, n;
int i;
/* Save space: see if the result is identical to one of the args. */
if (valtype == TREE_TYPE (t1) && !TYPE_ARG_TYPES (t2))
return build_type_attribute_variant (t1, attributes);
if (valtype == TREE_TYPE (t2) && !TYPE_ARG_TYPES (t1))
return build_type_attribute_variant (t2, attributes);
/* Simple way if one arg fails to specify argument types. */
if (TYPE_ARG_TYPES (t1) == 0)
{
t1 = build_function_type (valtype, TYPE_ARG_TYPES (t2));
t1 = build_type_attribute_variant (t1, attributes);
return qualify_type (t1, t2);
}
if (TYPE_ARG_TYPES (t2) == 0)
{
t1 = build_function_type (valtype, TYPE_ARG_TYPES (t1));
t1 = build_type_attribute_variant (t1, attributes);
return qualify_type (t1, t2);
}
/* If both args specify argument types, we must merge the two
lists, argument by argument. */
/* Tell global_bindings_p to return false so that variable_size
doesn't die on VLAs in parameter types. */
c_override_global_bindings_to_false = true;
len = list_length (p1);
newargs = 0;
for (i = 0; i < len; i++)
newargs = tree_cons (NULL_TREE, NULL_TREE, newargs);
n = newargs;
for (; p1;
p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n))
{
/* A null type means arg type is not specified.
Take whatever the other function type has. */
if (TREE_VALUE (p1) == 0)
{
TREE_VALUE (n) = TREE_VALUE (p2);
goto parm_done;
}
if (TREE_VALUE (p2) == 0)
{
TREE_VALUE (n) = TREE_VALUE (p1);
goto parm_done;
}
/* Given wait (union {union wait *u; int *i} *)
and wait (union wait *),
prefer union wait * as type of parm. */
if (TREE_CODE (TREE_VALUE (p1)) == UNION_TYPE
&& TREE_VALUE (p1) != TREE_VALUE (p2))
{
tree memb;
tree mv2 = TREE_VALUE (p2);
if (mv2 && mv2 != error_mark_node
&& TREE_CODE (mv2) != ARRAY_TYPE)
mv2 = TYPE_MAIN_VARIANT (mv2);
for (memb = TYPE_FIELDS (TREE_VALUE (p1));
memb; memb = TREE_CHAIN (memb))
{
tree mv3 = TREE_TYPE (memb);
if (mv3 && mv3 != error_mark_node
&& TREE_CODE (mv3) != ARRAY_TYPE)
mv3 = TYPE_MAIN_VARIANT (mv3);
if (comptypes (mv3, mv2))
{
TREE_VALUE (n) = composite_type (TREE_TYPE (memb),
TREE_VALUE (p2));
if (pedantic)
pedwarn ("function types not truly compatible in ISO C");
goto parm_done;
}
}
}
if (TREE_CODE (TREE_VALUE (p2)) == UNION_TYPE
&& TREE_VALUE (p2) != TREE_VALUE (p1))
{
tree memb;
tree mv1 = TREE_VALUE (p1);
if (mv1 && mv1 != error_mark_node
&& TREE_CODE (mv1) != ARRAY_TYPE)
mv1 = TYPE_MAIN_VARIANT (mv1);
for (memb = TYPE_FIELDS (TREE_VALUE (p2));
memb; memb = TREE_CHAIN (memb))
{
tree mv3 = TREE_TYPE (memb);
if (mv3 && mv3 != error_mark_node
&& TREE_CODE (mv3) != ARRAY_TYPE)
mv3 = TYPE_MAIN_VARIANT (mv3);
if (comptypes (mv3, mv1))
{
TREE_VALUE (n) = composite_type (TREE_TYPE (memb),
TREE_VALUE (p1));
if (pedantic)
pedwarn ("function types not truly compatible in ISO C");
goto parm_done;
}
}
}
TREE_VALUE (n) = composite_type (TREE_VALUE (p1), TREE_VALUE (p2));
parm_done: ;
}
c_override_global_bindings_to_false = false;
t1 = build_function_type (valtype, newargs);
t1 = qualify_type (t1, t2);
/* ... falls through ... */
}
default:
return build_type_attribute_variant (t1, attributes);
}
}
/* Return the type of a conditional expression between pointers to
possibly differently qualified versions of compatible types.
We assume that comp_target_types has already been done and returned
nonzero; if that isn't so, this may crash. */
static tree
common_pointer_type (tree t1, tree t2)
{
tree attributes;
tree pointed_to_1, mv1;
tree pointed_to_2, mv2;
tree target;
unsigned target_quals;
/* Save time if the two types are the same. */
if (t1 == t2) return t1;
/* If one type is nonsense, use the other. */
if (t1 == error_mark_node)
return t2;
if (t2 == error_mark_node)
return t1;
gcc_assert (TREE_CODE (t1) == POINTER_TYPE
&& TREE_CODE (t2) == POINTER_TYPE);
/* Merge the attributes. */
attributes = targetm.merge_type_attributes (t1, t2);
/* Find the composite type of the target types, and combine the
qualifiers of the two types' targets. Do not lose qualifiers on
array element types by taking the TYPE_MAIN_VARIANT. */
mv1 = pointed_to_1 = TREE_TYPE (t1);
mv2 = pointed_to_2 = TREE_TYPE (t2);
if (TREE_CODE (mv1) != ARRAY_TYPE)
mv1 = TYPE_MAIN_VARIANT (pointed_to_1);
if (TREE_CODE (mv2) != ARRAY_TYPE)
mv2 = TYPE_MAIN_VARIANT (pointed_to_2);
target = composite_type (mv1, mv2);
/* For function types do not merge const qualifiers, but drop them
if used inconsistently. The middle-end uses these to mark const
and noreturn functions. */
if (TREE_CODE (pointed_to_1) == FUNCTION_TYPE)
target_quals = TYPE_QUALS (pointed_to_1) & TYPE_QUALS (pointed_to_2);
else
target_quals = TYPE_QUALS (pointed_to_1) | TYPE_QUALS (pointed_to_2);
t1 = build_pointer_type (c_build_qualified_type (target, target_quals));
return build_type_attribute_variant (t1, attributes);
}
/* Return the common type for two arithmetic types under the usual
arithmetic conversions. The default conversions have already been
applied, and enumerated types converted to their compatible integer
types. The resulting type is unqualified and has no attributes.
This is the type for the result of most arithmetic operations
if the operands have the given two types. */
static tree
c_common_type (tree t1, tree t2)
{
enum tree_code code1;
enum tree_code code2;
/* If one type is nonsense, use the other. */
if (t1 == error_mark_node)
return t2;
if (t2 == error_mark_node)
return t1;
if (TYPE_QUALS (t1) != TYPE_UNQUALIFIED)
t1 = TYPE_MAIN_VARIANT (t1);
if (TYPE_QUALS (t2) != TYPE_UNQUALIFIED)
t2 = TYPE_MAIN_VARIANT (t2);
if (TYPE_ATTRIBUTES (t1) != NULL_TREE)
t1 = build_type_attribute_variant (t1, NULL_TREE);
if (TYPE_ATTRIBUTES (t2) != NULL_TREE)
t2 = build_type_attribute_variant (t2, NULL_TREE);
/* Save time if the two types are the same. */
if (t1 == t2) return t1;
code1 = TREE_CODE (t1);
code2 = TREE_CODE (t2);
gcc_assert (code1 == VECTOR_TYPE || code1 == COMPLEX_TYPE
|| code1 == REAL_TYPE || code1 == INTEGER_TYPE);
gcc_assert (code2 == VECTOR_TYPE || code2 == COMPLEX_TYPE
|| code2 == REAL_TYPE || code2 == INTEGER_TYPE);
/* When one operand is a decimal float type, the other operand cannot be
a generic float type or a complex type. We also disallow vector types
here. */
if ((DECIMAL_FLOAT_TYPE_P (t1) || DECIMAL_FLOAT_TYPE_P (t2))
&& !(DECIMAL_FLOAT_TYPE_P (t1) && DECIMAL_FLOAT_TYPE_P (t2)))
{
if (code1 == VECTOR_TYPE || code2 == VECTOR_TYPE)
{
error ("can%'t mix operands of decimal float and vector types");
return error_mark_node;
}
if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
{
error ("can%'t mix operands of decimal float and complex types");
return error_mark_node;
}
if (code1 == REAL_TYPE && code2 == REAL_TYPE)
{
error ("can%'t mix operands of decimal float and other float types");
return error_mark_node;
}
}
/* If one type is a vector type, return that type. (How the usual
arithmetic conversions apply to the vector types extension is not
precisely specified.) */
if (code1 == VECTOR_TYPE)
return t1;
if (code2 == VECTOR_TYPE)
return t2;
/* If one type is complex, form the common type of the non-complex
components, then make that complex. Use T1 or T2 if it is the
required type. */
if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
{
tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1;
tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2;
tree subtype = c_common_type (subtype1, subtype2);
if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype)
return t1;
else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype)
return t2;
else
return build_complex_type (subtype);
}
/* If only one is real, use it as the result. */
if (code1 == REAL_TYPE && code2 != REAL_TYPE)
return t1;
if (code2 == REAL_TYPE && code1 != REAL_TYPE)
return t2;
/* If both are real and either are decimal floating point types, use
the decimal floating point type with the greater precision. */
if (code1 == REAL_TYPE && code2 == REAL_TYPE)
{
if (TYPE_MAIN_VARIANT (t1) == dfloat128_type_node
|| TYPE_MAIN_VARIANT (t2) == dfloat128_type_node)
return dfloat128_type_node;
else if (TYPE_MAIN_VARIANT (t1) == dfloat64_type_node
|| TYPE_MAIN_VARIANT (t2) == dfloat64_type_node)
return dfloat64_type_node;
else if (TYPE_MAIN_VARIANT (t1) == dfloat32_type_node
|| TYPE_MAIN_VARIANT (t2) == dfloat32_type_node)
return dfloat32_type_node;
}
/* Both real or both integers; use the one with greater precision. */
if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2))
return t1;
else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1))
return t2;
/* Same precision. Prefer long longs to longs to ints when the
same precision, following the C99 rules on integer type rank
(which are equivalent to the C90 rules for C90 types). */
if (TYPE_MAIN_VARIANT (t1) == long_long_unsigned_type_node
|| TYPE_MAIN_VARIANT (t2) == long_long_unsigned_type_node)
return long_long_unsigned_type_node;
if (TYPE_MAIN_VARIANT (t1) == long_long_integer_type_node
|| TYPE_MAIN_VARIANT (t2) == long_long_integer_type_node)
{
if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
return long_long_unsigned_type_node;
else
return long_long_integer_type_node;
}
if (TYPE_MAIN_VARIANT (t1) == long_unsigned_type_node
|| TYPE_MAIN_VARIANT (t2) == long_unsigned_type_node)
return long_unsigned_type_node;
if (TYPE_MAIN_VARIANT (t1) == long_integer_type_node
|| TYPE_MAIN_VARIANT (t2) == long_integer_type_node)
{
/* But preserve unsignedness from the other type,
since long cannot hold all the values of an unsigned int. */
if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
return long_unsigned_type_node;
else
return long_integer_type_node;
}
/* Likewise, prefer long double to double even if same size. */
if (TYPE_MAIN_VARIANT (t1) == long_double_type_node
|| TYPE_MAIN_VARIANT (t2) == long_double_type_node)
return long_double_type_node;
/* Otherwise prefer the unsigned one. */
if (TYPE_UNSIGNED (t1))
return t1;
else
return t2;
}
/* Wrapper around c_common_type that is used by c-common.c and other
front end optimizations that remove promotions. ENUMERAL_TYPEs
are allowed here and are converted to their compatible integer types.
BOOLEAN_TYPEs are allowed here and return either boolean_type_node or
preferably a non-Boolean type as the common type. */
tree
common_type (tree t1, tree t2)
{
if (TREE_CODE (t1) == ENUMERAL_TYPE)
t1 = c_common_type_for_size (TYPE_PRECISION (t1), 1);
if (TREE_CODE (t2) == ENUMERAL_TYPE)
t2 = c_common_type_for_size (TYPE_PRECISION (t2), 1);
/* If both types are BOOLEAN_TYPE, then return boolean_type_node. */
if (TREE_CODE (t1) == BOOLEAN_TYPE
&& TREE_CODE (t2) == BOOLEAN_TYPE)
return boolean_type_node;
/* If either type is BOOLEAN_TYPE, then return the other. */
if (TREE_CODE (t1) == BOOLEAN_TYPE)
return t2;
if (TREE_CODE (t2) == BOOLEAN_TYPE)
return t1;
return c_common_type (t1, t2);
}
/* Return 1 if TYPE1 and TYPE2 are compatible types for assignment
or various other operations. Return 2 if they are compatible
but a warning may be needed if you use them together. */
int
comptypes (tree type1, tree type2)
{
const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base;
int val;
val = comptypes_internal (type1, type2);
free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1);
return val;
}
/* Return 1 if TYPE1 and TYPE2 are compatible types for assignment
or various other operations. Return 2 if they are compatible
but a warning may be needed if you use them together. This
differs from comptypes, in that we don't free the seen types. */
static int
comptypes_internal (tree type1, tree type2)
{
tree t1 = type1;
tree t2 = type2;
int attrval, val;
/* Suppress errors caused by previously reported errors. */
if (t1 == t2 || !t1 || !t2
|| TREE_CODE (t1) == ERROR_MARK || TREE_CODE (t2) == ERROR_MARK)
return 1;
/* If either type is the internal version of sizetype, return the
language version. */
if (TREE_CODE (t1) == INTEGER_TYPE && TYPE_IS_SIZETYPE (t1)
&& TYPE_ORIG_SIZE_TYPE (t1))
t1 = TYPE_ORIG_SIZE_TYPE (t1);
if (TREE_CODE (t2) == INTEGER_TYPE && TYPE_IS_SIZETYPE (t2)
&& TYPE_ORIG_SIZE_TYPE (t2))
t2 = TYPE_ORIG_SIZE_TYPE (t2);
/* Enumerated types are compatible with integer types, but this is
not transitive: two enumerated types in the same translation unit
are compatible with each other only if they are the same type. */
if (TREE_CODE (t1) == ENUMERAL_TYPE && TREE_CODE (t2) != ENUMERAL_TYPE)
t1 = c_common_type_for_size (TYPE_PRECISION (t1), TYPE_UNSIGNED (t1));
else if (TREE_CODE (t2) == ENUMERAL_TYPE && TREE_CODE (t1) != ENUMERAL_TYPE)
t2 = c_common_type_for_size (TYPE_PRECISION (t2), TYPE_UNSIGNED (t2));
if (t1 == t2)
return 1;
/* Different classes of types can't be compatible. */
if (TREE_CODE (t1) != TREE_CODE (t2))
return 0;
/* Qualifiers must match. C99 6.7.3p9 */
if (TYPE_QUALS (t1) != TYPE_QUALS (t2))
return 0;
/* Allow for two different type nodes which have essentially the same
definition. Note that we already checked for equality of the type
qualifiers (just above). */
if (TREE_CODE (t1) != ARRAY_TYPE
&& TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
return 1;
/* 1 if no need for warning yet, 2 if warning cause has been seen. */
if (!(attrval = targetm.comp_type_attributes (t1, t2)))
return 0;
/* 1 if no need for warning yet, 2 if warning cause has been seen. */
val = 0;
switch (TREE_CODE (t1))
{
case POINTER_TYPE:
/* Do not remove mode or aliasing information. */
if (TYPE_MODE (t1) != TYPE_MODE (t2)
|| TYPE_REF_CAN_ALIAS_ALL (t1) != TYPE_REF_CAN_ALIAS_ALL (t2))
break;
val = (TREE_TYPE (t1) == TREE_TYPE (t2)
? 1 : comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2)));
break;
case FUNCTION_TYPE:
val = function_types_compatible_p (t1, t2);
break;
case ARRAY_TYPE:
{
tree d1 = TYPE_DOMAIN (t1);
tree d2 = TYPE_DOMAIN (t2);
bool d1_variable, d2_variable;
bool d1_zero, d2_zero;
val = 1;
/* Target types must match incl. qualifiers. */
if (TREE_TYPE (t1) != TREE_TYPE (t2)
&& 0 == (val = comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2))))
return 0;
/* Sizes must match unless one is missing or variable. */
if (d1 == 0 || d2 == 0 || d1 == d2)
break;
d1_zero = !TYPE_MAX_VALUE (d1);
d2_zero = !TYPE_MAX_VALUE (d2);
d1_variable = (!d1_zero
&& (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST
|| TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST));
d2_variable = (!d2_zero
&& (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST
|| TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST));
d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1));
d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2));
if (d1_variable || d2_variable)
break;
if (d1_zero && d2_zero)
break;
if (d1_zero || d2_zero
|| !tree_int_cst_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2))
|| !tree_int_cst_equal (TYPE_MAX_VALUE (d1), TYPE_MAX_VALUE (d2)))
val = 0;
break;
}
case ENUMERAL_TYPE:
case RECORD_TYPE:
case UNION_TYPE:
if (val != 1 && !same_translation_unit_p (t1, t2))
{
tree a1 = TYPE_ATTRIBUTES (t1);
tree a2 = TYPE_ATTRIBUTES (t2);
if (! attribute_list_contained (a1, a2)
&& ! attribute_list_contained (a2, a1))
break;
if (attrval != 2)
return tagged_types_tu_compatible_p (t1, t2);
val = tagged_types_tu_compatible_p (t1, t2);
}
break;
case VECTOR_TYPE:
val = TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2)
&& comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2));
break;
default:
break;
}
return attrval == 2 && val == 1 ? 2 : val;
}
/* Return 1 if TTL and TTR are pointers to types that are equivalent,
ignoring their qualifiers. */
static int
comp_target_types (tree ttl, tree ttr)
{
int val;
tree mvl, mvr;
/* Do not lose qualifiers on element types of array types that are
pointer targets by taking their TYPE_MAIN_VARIANT. */
mvl = TREE_TYPE (ttl);
mvr = TREE_TYPE (ttr);
if (TREE_CODE (mvl) != ARRAY_TYPE)
mvl = TYPE_MAIN_VARIANT (mvl);
if (TREE_CODE (mvr) != ARRAY_TYPE)
mvr = TYPE_MAIN_VARIANT (mvr);
val = comptypes (mvl, mvr);
if (val == 2 && pedantic)
pedwarn ("types are not quite compatible");
return val;
}
/* Subroutines of `comptypes'. */
/* Determine whether two trees derive from the same translation unit.
If the CONTEXT chain ends in a null, that tree's context is still
being parsed, so if two trees have context chains ending in null,
they're in the same translation unit. */
int
same_translation_unit_p (tree t1, tree t2)
{
while (t1 && TREE_CODE (t1) != TRANSLATION_UNIT_DECL)
switch (TREE_CODE_CLASS (TREE_CODE (t1)))
{
case tcc_declaration:
t1 = DECL_CONTEXT (t1); break;
case tcc_type:
t1 = TYPE_CONTEXT (t1); break;
case tcc_exceptional:
t1 = BLOCK_SUPERCONTEXT (t1); break; /* assume block */
default: gcc_unreachable ();
}
while (t2 && TREE_CODE (t2) != TRANSLATION_UNIT_DECL)
switch (TREE_CODE_CLASS (TREE_CODE (t2)))
{
case tcc_declaration:
t2 = DECL_CONTEXT (t2); break;
case tcc_type:
t2 = TYPE_CONTEXT (t2); break;
case tcc_exceptional:
t2 = BLOCK_SUPERCONTEXT (t2); break; /* assume block */
default: gcc_unreachable ();
}
return t1 == t2;
}
/* Allocate the seen two types, assuming that they are compatible. */
static struct tagged_tu_seen_cache *
alloc_tagged_tu_seen_cache (tree t1, tree t2)
{
struct tagged_tu_seen_cache *tu = XNEW (struct tagged_tu_seen_cache);
tu->next = tagged_tu_seen_base;
tu->t1 = t1;
tu->t2 = t2;
tagged_tu_seen_base = tu;
/* The C standard says that two structures in different translation
units are compatible with each other only if the types of their
fields are compatible (among other things). We assume that they
are compatible until proven otherwise when building the cache.
An example where this can occur is:
struct a
{
struct a *next;
};
If we are comparing this against a similar struct in another TU,
and did not assume they were compatible, we end up with an infinite
loop. */
tu->val = 1;
return tu;
}
/* Free the seen types until we get to TU_TIL. */
static void
free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *tu_til)
{
const struct tagged_tu_seen_cache *tu = tagged_tu_seen_base;
while (tu != tu_til)
{
struct tagged_tu_seen_cache *tu1 = (struct tagged_tu_seen_cache*)tu;
tu = tu1->next;
free (tu1);
}
tagged_tu_seen_base = tu_til;
}
/* Return 1 if two 'struct', 'union', or 'enum' types T1 and T2 are
compatible. If the two types are not the same (which has been
checked earlier), this can only happen when multiple translation
units are being compiled. See C99 6.2.7 paragraph 1 for the exact
rules. */
static int
tagged_types_tu_compatible_p (tree t1, tree t2)
{
tree s1, s2;
bool needs_warning = false;
/* We have to verify that the tags of the types are the same. This
is harder than it looks because this may be a typedef, so we have
to go look at the original type. It may even be a typedef of a
typedef...
In the case of compiler-created builtin structs the TYPE_DECL
may be a dummy, with no DECL_ORIGINAL_TYPE. Don't fault. */
while (TYPE_NAME (t1)
&& TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL
&& DECL_ORIGINAL_TYPE (TYPE_NAME (t1)))
t1 = DECL_ORIGINAL_TYPE (TYPE_NAME (t1));
while (TYPE_NAME (t2)
&& TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL
&& DECL_ORIGINAL_TYPE (TYPE_NAME (t2)))
t2 = DECL_ORIGINAL_TYPE (TYPE_NAME (t2));
/* C90 didn't have the requirement that the two tags be the same. */
if (flag_isoc99 && TYPE_NAME (t1) != TYPE_NAME (t2))
return 0;
/* C90 didn't say what happened if one or both of the types were
incomplete; we choose to follow C99 rules here, which is that they
are compatible. */
if (TYPE_SIZE (t1) == NULL
|| TYPE_SIZE (t2) == NULL)
return 1;
{
const struct tagged_tu_seen_cache * tts_i;
for (tts_i = tagged_tu_seen_base; tts_i != NULL; tts_i = tts_i->next)
if (tts_i->t1 == t1 && tts_i->t2 == t2)
return tts_i->val;
}
switch (TREE_CODE (t1))
{
case ENUMERAL_TYPE:
{
struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2);
/* Speed up the case where the type values are in the same order. */
tree tv1 = TYPE_VALUES (t1);
tree tv2 = TYPE_VALUES (t2);
if (tv1 == tv2)
{
return 1;
}
for (;tv1 && tv2; tv1 = TREE_CHAIN (tv1), tv2 = TREE_CHAIN (tv2))
{
if (TREE_PURPOSE (tv1) != TREE_PURPOSE (tv2))
break;
if (simple_cst_equal (TREE_VALUE (tv1), TREE_VALUE (tv2)) != 1)
{
tu->val = 0;
return 0;
}
}
if (tv1 == NULL_TREE && tv2 == NULL_TREE)
{
return 1;
}
if (tv1 == NULL_TREE || tv2 == NULL_TREE)
{
tu->val = 0;
return 0;
}
if (list_length (TYPE_VALUES (t1)) != list_length (TYPE_VALUES (t2)))
{
tu->val = 0;
return 0;
}
for (s1 = TYPE_VALUES (t1); s1; s1 = TREE_CHAIN (s1))
{
s2 = purpose_member (TREE_PURPOSE (s1), TYPE_VALUES (t2));
if (s2 == NULL
|| simple_cst_equal (TREE_VALUE (s1), TREE_VALUE (s2)) != 1)
{
tu->val = 0;
return 0;
}
}
return 1;
}
case UNION_TYPE:
{
struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2);
if (list_length (TYPE_FIELDS (t1)) != list_length (TYPE_FIELDS (t2)))
{
tu->val = 0;
return 0;
}
/* Speed up the common case where the fields are in the same order. */
for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2); s1 && s2;
s1 = TREE_CHAIN (s1), s2 = TREE_CHAIN (s2))
{
int result;
if (DECL_NAME (s1) == NULL
|| DECL_NAME (s1) != DECL_NAME (s2))
break;
result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2));
if (result == 0)
{
tu->val = 0;
return 0;
}
if (result == 2)
needs_warning = true;
if (TREE_CODE (s1) == FIELD_DECL
&& simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1),
DECL_FIELD_BIT_OFFSET (s2)) != 1)
{
tu->val = 0;
return 0;
}
}
if (!s1 && !s2)
{
tu->val = needs_warning ? 2 : 1;
return tu->val;
}
for (s1 = TYPE_FIELDS (t1); s1; s1 = TREE_CHAIN (s1))
{
bool ok = false;
if (DECL_NAME (s1) != NULL)
for (s2 = TYPE_FIELDS (t2); s2; s2 = TREE_CHAIN (s2))
if (DECL_NAME (s1) == DECL_NAME (s2))
{
int result;
result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2));
if (result == 0)
{
tu->val = 0;
return 0;
}
if (result == 2)
needs_warning = true;
if (TREE_CODE (s1) == FIELD_DECL
&& simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1),
DECL_FIELD_BIT_OFFSET (s2)) != 1)
break;
ok = true;
break;
}
if (!ok)
{
tu->val = 0;
return 0;
}
}
tu->val = needs_warning ? 2 : 10;
return tu->val;
}
case RECORD_TYPE:
{
struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2);
for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2);
s1 && s2;
s1 = TREE_CHAIN (s1), s2 = TREE_CHAIN (s2))
{
int result;
if (TREE_CODE (s1) != TREE_CODE (s2)
|| DECL_NAME (s1) != DECL_NAME (s2))
break;
result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2));
if (result == 0)
break;
if (result == 2)
needs_warning = true;
if (TREE_CODE (s1) == FIELD_DECL
&& simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1),
DECL_FIELD_BIT_OFFSET (s2)) != 1)
break;
}
if (s1 && s2)
tu->val = 0;
else
tu->val = needs_warning ? 2 : 1;
return tu->val;
}
default:
gcc_unreachable ();
}
}
/* Return 1 if two function types F1 and F2 are compatible.
If either type specifies no argument types,
the other must specify a fixed number of self-promoting arg types.
Otherwise, if one type specifies only the number of arguments,
the other must specify that number of self-promoting arg types.
Otherwise, the argument types must match. */
static int
function_types_compatible_p (tree f1, tree f2)
{
tree args1, args2;
/* 1 if no need for warning yet, 2 if warning cause has been seen. */
int val = 1;
int val1;
tree ret1, ret2;
ret1 = TREE_TYPE (f1);
ret2 = TREE_TYPE (f2);
/* 'volatile' qualifiers on a function's return type used to mean
the function is noreturn. */
if (TYPE_VOLATILE (ret1) != TYPE_VOLATILE (ret2))
pedwarn ("function return types not compatible due to %<volatile%>");
if (TYPE_VOLATILE (ret1))
ret1 = build_qualified_type (TYPE_MAIN_VARIANT (ret1),
TYPE_QUALS (ret1) & ~TYPE_QUAL_VOLATILE);
if (TYPE_VOLATILE (ret2))
ret2 = build_qualified_type (TYPE_MAIN_VARIANT (ret2),
TYPE_QUALS (ret2) & ~TYPE_QUAL_VOLATILE);
val = comptypes_internal (ret1, ret2);
if (val == 0)
return 0;
args1 = TYPE_ARG_TYPES (f1);
args2 = TYPE_ARG_TYPES (f2);
/* An unspecified parmlist matches any specified parmlist
whose argument types don't need default promotions. */
if (args1 == 0)
{
if (!self_promoting_args_p (args2))
return 0;
/* If one of these types comes from a non-prototype fn definition,
compare that with the other type's arglist.
If they don't match, ask for a warning (but no error). */
if (TYPE_ACTUAL_ARG_TYPES (f1)
&& 1 != type_lists_compatible_p (args2, TYPE_ACTUAL_ARG_TYPES (f1)))
val = 2;
return val;
}
if (args2 == 0)
{
if (!self_promoting_args_p (args1))
return 0;
if (TYPE_ACTUAL_ARG_TYPES (f2)
&& 1 != type_lists_compatible_p (args1, TYPE_ACTUAL_ARG_TYPES (f2)))
val = 2;
return val;
}
/* Both types have argument lists: compare them and propagate results. */
val1 = type_lists_compatible_p (args1, args2);
return val1 != 1 ? val1 : val;
}
/* Check two lists of types for compatibility,
returning 0 for incompatible, 1 for compatible,
or 2 for compatible with warning. */
static int
type_lists_compatible_p (tree args1, tree args2)
{
/* 1 if no need for warning yet, 2 if warning cause has been seen. */
int val = 1;
int newval = 0;
while (1)
{
tree a1, mv1, a2, mv2;
if (args1 == 0 && args2 == 0)
return val;
/* If one list is shorter than the other,
they fail to match. */
if (args1 == 0 || args2 == 0)
return 0;
mv1 = a1 = TREE_VALUE (args1);
mv2 = a2 = TREE_VALUE (args2);
if (mv1 && mv1 != error_mark_node && TREE_CODE (mv1) != ARRAY_TYPE)
mv1 = TYPE_MAIN_VARIANT (mv1);
if (mv2 && mv2 != error_mark_node && TREE_CODE (mv2) != ARRAY_TYPE)
mv2 = TYPE_MAIN_VARIANT (mv2);
/* A null pointer instead of a type
means there is supposed to be an argument
but nothing is specified about what type it has.
So match anything that self-promotes. */
if (a1 == 0)
{
if (c_type_promotes_to (a2) != a2)
return 0;
}
else if (a2 == 0)
{
if (c_type_promotes_to (a1) != a1)
return 0;
}
/* If one of the lists has an error marker, ignore this arg. */
else if (TREE_CODE (a1) == ERROR_MARK
|| TREE_CODE (a2) == ERROR_MARK)
;
else if (!(newval = comptypes_internal (mv1, mv2)))
{
/* Allow wait (union {union wait *u; int *i} *)
and wait (union wait *) to be compatible. */
if (TREE_CODE (a1) == UNION_TYPE
&& (TYPE_NAME (a1) == 0
|| TYPE_TRANSPARENT_UNION (a1))
&& TREE_CODE (TYPE_SIZE (a1)) == INTEGER_CST
&& tree_int_cst_equal (TYPE_SIZE (a1),
TYPE_SIZE (a2)))
{
tree memb;
for (memb = TYPE_FIELDS (a1);
memb; memb = TREE_CHAIN (memb))
{
tree mv3 = TREE_TYPE (memb);
if (mv3 && mv3 != error_mark_node
&& TREE_CODE (mv3) != ARRAY_TYPE)
mv3 = TYPE_MAIN_VARIANT (mv3);
if (comptypes_internal (mv3, mv2))
break;
}
if (memb == 0)
return 0;
}
else if (TREE_CODE (a2) == UNION_TYPE
&& (TYPE_NAME (a2) == 0
|| TYPE_TRANSPARENT_UNION (a2))
&& TREE_CODE (TYPE_SIZE (a2)) == INTEGER_CST
&& tree_int_cst_equal (TYPE_SIZE (a2),
TYPE_SIZE (a1)))
{
tree memb;
for (memb = TYPE_FIELDS (a2);
memb; memb = TREE_CHAIN (memb))
{
tree mv3 = TREE_TYPE (memb);
if (mv3 && mv3 != error_mark_node
&& TREE_CODE (mv3) != ARRAY_TYPE)
mv3 = TYPE_MAIN_VARIANT (mv3);
if (comptypes_internal (mv3, mv1))
break;
}
if (memb == 0)
return 0;
}
else
return 0;
}
/* comptypes said ok, but record if it said to warn. */
if (newval > val)
val = newval;
args1 = TREE_CHAIN (args1);
args2 = TREE_CHAIN (args2);
}
}
/* Compute the size to increment a pointer by. */
static tree
c_size_in_bytes (tree type)
{
enum tree_code code = TREE_CODE (type);
if (code == FUNCTION_TYPE || code == VOID_TYPE || code == ERROR_MARK)
return size_one_node;
if (!COMPLETE_OR_VOID_TYPE_P (type))
{
error ("arithmetic on pointer to an incomplete type");
return size_one_node;
}
/* Convert in case a char is more than one unit. */
return size_binop (CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
size_int (TYPE_PRECISION (char_type_node)
/ BITS_PER_UNIT));
}
/* Return either DECL or its known constant value (if it has one). */
tree
decl_constant_value (tree decl)
{
if (/* Don't change a variable array bound or initial value to a constant
in a place where a variable is invalid. Note that DECL_INITIAL
isn't valid for a PARM_DECL. */
current_function_decl != 0
&& TREE_CODE (decl) != PARM_DECL
&& !TREE_THIS_VOLATILE (decl)
&& TREE_READONLY (decl)
&& DECL_INITIAL (decl) != 0
&& TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
/* This is invalid if initial value is not constant.
If it has either a function call, a memory reference,
or a variable, then re-evaluating it could give different results. */
&& TREE_CONSTANT (DECL_INITIAL (decl))
/* Check for cases where this is sub-optimal, even though valid. */
&& TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
return DECL_INITIAL (decl);
return decl;
}
/* Return either DECL or its known constant value (if it has one), but
return DECL if pedantic or DECL has mode BLKmode. This is for
bug-compatibility with the old behavior of decl_constant_value
(before GCC 3.0); every use of this function is a bug and it should
be removed before GCC 3.1. It is not appropriate to use pedantic
in a way that affects optimization, and BLKmode is probably not the
right test for avoiding misoptimizations either. */
static tree
decl_constant_value_for_broken_optimization (tree decl)
{
tree ret;
if (pedantic || DECL_MODE (decl) == BLKmode)
return decl;
ret = decl_constant_value (decl);
/* Avoid unwanted tree sharing between the initializer and current
function's body where the tree can be modified e.g. by the
gimplifier. */
if (ret != decl && TREE_STATIC (decl))
ret = unshare_expr (ret);
return ret;
}
/* Convert the array expression EXP to a pointer. */
static tree
array_to_pointer_conversion (tree exp)
{
tree orig_exp = exp;
tree type = TREE_TYPE (exp);
tree adr;
tree restype = TREE_TYPE (type);
tree ptrtype;
gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
STRIP_TYPE_NOPS (exp);
if (TREE_NO_WARNING (orig_exp))
TREE_NO_WARNING (exp) = 1;
ptrtype = build_pointer_type (restype);
if (TREE_CODE (exp) == INDIRECT_REF)
return convert (ptrtype, TREE_OPERAND (exp, 0));
if (TREE_CODE (exp) == VAR_DECL)
{
/* We are making an ADDR_EXPR of ptrtype. This is a valid
ADDR_EXPR because it's the best way of representing what
happens in C when we take the address of an array and place
it in a pointer to the element type. */
adr = build1 (ADDR_EXPR, ptrtype, exp);
if (!c_mark_addressable (exp))
return error_mark_node;
TREE_SIDE_EFFECTS (adr) = 0; /* Default would be, same as EXP. */
return adr;
}
/* This way is better for a COMPONENT_REF since it can
simplify the offset for a component. */
adr = build_unary_op (ADDR_EXPR, exp, 1);
return convert (ptrtype, adr);
}
/* Convert the function expression EXP to a pointer. */
static tree
function_to_pointer_conversion (tree exp)
{
tree orig_exp = exp;
gcc_assert (TREE_CODE (TREE_TYPE (exp)) == FUNCTION_TYPE);
STRIP_TYPE_NOPS (exp);
if (TREE_NO_WARNING (orig_exp))
TREE_NO_WARNING (exp) = 1;
return build_unary_op (ADDR_EXPR, exp, 0);
}
/* Perform the default conversion of arrays and functions to pointers.
Return the result of converting EXP. For any other expression, just
return EXP after removing NOPs. */
struct c_expr
default_function_array_conversion (struct c_expr exp)
{
tree orig_exp = exp.value;
tree type = TREE_TYPE (exp.value);
enum tree_code code = TREE_CODE (type);
switch (code)
{
case ARRAY_TYPE:
{
bool not_lvalue = false;
bool lvalue_array_p;
while ((TREE_CODE (exp.value) == NON_LVALUE_EXPR
|| TREE_CODE (exp.value) == NOP_EXPR
|| TREE_CODE (exp.value) == CONVERT_EXPR)
&& TREE_TYPE (TREE_OPERAND (exp.value, 0)) == type)
{
if (TREE_CODE (exp.value) == NON_LVALUE_EXPR)
not_lvalue = true;
exp.value = TREE_OPERAND (exp.value, 0);
}
if (TREE_NO_WARNING (orig_exp))
TREE_NO_WARNING (exp.value) = 1;
lvalue_array_p = !not_lvalue && lvalue_p (exp.value);
if (!flag_isoc99 && !lvalue_array_p)
{
/* Before C99, non-lvalue arrays do not decay to pointers.
Normally, using such an array would be invalid; but it can
be used correctly inside sizeof or as a statement expression.
Thus, do not give an error here; an error will result later. */
return exp;
}
exp.value = array_to_pointer_conversion (exp.value);
}
break;
case FUNCTION_TYPE:
exp.value = function_to_pointer_conversion (exp.value);
break;
default:
STRIP_TYPE_NOPS (exp.value);
if (TREE_NO_WARNING (orig_exp))
TREE_NO_WARNING (exp.value) = 1;
break;
}
return exp;
}
/* EXP is an expression of integer type. Apply the integer promotions
to it and return the promoted value. */
tree
perform_integral_promotions (tree exp)
{
tree type = TREE_TYPE (exp);
enum tree_code code = TREE_CODE (type);
gcc_assert (INTEGRAL_TYPE_P (type));
/* Normally convert enums to int,
but convert wide enums to something wider. */
if (code == ENUMERAL_TYPE)
{
type = c_common_type_for_size (MAX (TYPE_PRECISION (type),
TYPE_PRECISION (integer_type_node)),
((TYPE_PRECISION (type)
>= TYPE_PRECISION (integer_type_node))
&& TYPE_UNSIGNED (type)));
return convert (type, exp);
}
/* ??? This should no longer be needed now bit-fields have their
proper types. */
if (TREE_CODE (exp) == COMPONENT_REF
&& DECL_C_BIT_FIELD (TREE_OPERAND (exp, 1))
/* If it's thinner than an int, promote it like a
c_promoting_integer_type_p, otherwise leave it alone. */
&& 0 > compare_tree_int (DECL_SIZE (TREE_OPERAND (exp, 1)),
TYPE_PRECISION (integer_type_node)))
return convert (integer_type_node, exp);
if (c_promoting_integer_type_p (type))
{
/* Preserve unsignedness if not really getting any wider. */
if (TYPE_UNSIGNED (type)
&& TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node))
return convert (unsigned_type_node, exp);
return convert (integer_type_node, exp);
}
return exp;
}
/* Perform default promotions for C data used in expressions.
Enumeral types or short or char are converted to int.
In addition, manifest constants symbols are replaced by their values. */
tree
default_conversion (tree exp)
{
tree orig_exp;
tree type = TREE_TYPE (exp);
enum tree_code code = TREE_CODE (type);
/* Functions and arrays have been converted during parsing. */
gcc_assert (code != FUNCTION_TYPE);
if (code == ARRAY_TYPE)
return exp;
/* Constants can be used directly unless they're not loadable. */
if (TREE_CODE (exp) == CONST_DECL)
exp = DECL_INITIAL (exp);
/* Replace a nonvolatile const static variable with its value unless
it is an array, in which case we must be sure that taking the
address of the array produces consistent results. */
else if (optimize && TREE_CODE (exp) == VAR_DECL && code != ARRAY_TYPE)
{
exp = decl_constant_value_for_broken_optimization (exp);
type = TREE_TYPE (exp);
}
/* Strip no-op conversions. */
orig_exp = exp;
STRIP_TYPE_NOPS (exp);
if (TREE_NO_WARNING (orig_exp))
TREE_NO_WARNING (exp) = 1;
if (code == VOID_TYPE)
{
error ("void value not ignored as it ought to be");
return error_mark_node;
}
exp = require_complete_type (exp);
if (exp == error_mark_node)
return error_mark_node;
if (INTEGRAL_TYPE_P (type))
return perform_integral_promotions (exp);
return exp;
}
/* Look up COMPONENT in a structure or union DECL.
If the component name is not found, returns NULL_TREE. Otherwise,
the return value is a TREE_LIST, with each TREE_VALUE a FIELD_DECL
stepping down the chain to the component, which is in the last
TREE_VALUE of the list. Normally the list is of length one, but if
the component is embedded within (nested) anonymous structures or
unions, the list steps down the chain to the component. */
static tree
lookup_field (tree decl, tree component)
{
tree type = TREE_TYPE (decl);
tree field;
/* If TYPE_LANG_SPECIFIC is set, then it is a sorted array of pointers
to the field elements. Use a binary search on this array to quickly
find the element. Otherwise, do a linear search. TYPE_LANG_SPECIFIC
will always be set for structures which have many elements. */
if (TYPE_LANG_SPECIFIC (type) && TYPE_LANG_SPECIFIC (type)->s)
{
int bot, top, half;
tree *field_array = &TYPE_LANG_SPECIFIC (type)->s->elts[0];
field = TYPE_FIELDS (type);
bot = 0;
top = TYPE_LANG_SPECIFIC (type)->s->len;
while (top - bot > 1)
{
half = (top - bot + 1) >> 1;
field = field_array[bot+half];
if (DECL_NAME (field) == NULL_TREE)
{
/* Step through all anon unions in linear fashion. */
while (DECL_NAME (field_array[bot]) == NULL_TREE)
{
field = field_array[bot++];
if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE
|| TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
{
tree anon = lookup_field (field, component);
if (anon)
return tree_cons (NULL_TREE, field, anon);
}
}
/* Entire record is only anon unions. */
if (bot > top)
return NULL_TREE;
/* Restart the binary search, with new lower bound. */
continue;
}
if (DECL_NAME (field) == component)
break;
if (DECL_NAME (field) < component)
bot += half;
else
top = bot + half;
}
if (DECL_NAME (field_array[bot]) == component)
field = field_array[bot];
else if (DECL_NAME (field) != component)
return NULL_TREE;
}
else
{
for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
{
if (DECL_NAME (field) == NULL_TREE
&& (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE
|| TREE_CODE (TREE_TYPE (field)) == UNION_TYPE))
{
tree anon = lookup_field (field, component);
if (anon)
return tree_cons (NULL_TREE, field, anon);
}
if (DECL_NAME (field) == component)
break;
}
if (field == NULL_TREE)
return NULL_TREE;
}
return tree_cons (NULL_TREE, field, NULL_TREE);
}
/* Make an expression to refer to the COMPONENT field of
structure or union value DATUM. COMPONENT is an IDENTIFIER_NODE. */
tree
build_component_ref (tree datum, tree component)
{
tree type = TREE_TYPE (datum);
enum tree_code code = TREE_CODE (type);
tree field = NULL;
tree ref;
if (!objc_is_public (datum, component))
return error_mark_node;
/* See if there is a field or component with name COMPONENT. */
if (code == RECORD_TYPE || code == UNION_TYPE)
{
if (!COMPLETE_TYPE_P (type))
{
c_incomplete_type_error (NULL_TREE, type);
return error_mark_node;
}
field = lookup_field (datum, component);
if (!field)
{
error ("%qT has no member named %qE", type, component);
return error_mark_node;
}
/* Chain the COMPONENT_REFs if necessary down to the FIELD.
This might be better solved in future the way the C++ front
end does it - by giving the anonymous entities each a
separate name and type, and then have build_component_ref
recursively call itself. We can't do that here. */
do
{
tree subdatum = TREE_VALUE (field);
int quals;
tree subtype;
if (TREE_TYPE (subdatum) == error_mark_node)
return error_mark_node;
quals = TYPE_QUALS (strip_array_types (TREE_TYPE (subdatum)));
quals |= TYPE_QUALS (TREE_TYPE (datum));
subtype = c_build_qualified_type (TREE_TYPE (subdatum), quals);
ref = build3 (COMPONENT_REF, subtype, datum, subdatum,
NULL_TREE);
if (TREE_READONLY (datum) || TREE_READONLY (subdatum))
TREE_READONLY (ref) = 1;
if (TREE_THIS_VOLATILE (datum) || TREE_THIS_VOLATILE (subdatum))
TREE_THIS_VOLATILE (ref) = 1;
if (TREE_DEPRECATED (subdatum))
warn_deprecated_use (subdatum);
datum = ref;
field = TREE_CHAIN (field);
}
while (field);
return ref;
}
else if (code != ERROR_MARK)
error ("request for member %qE in something not a structure or union",
component);
return error_mark_node;
}
/* Given an expression PTR for a pointer, return an expression
for the value pointed to.
ERRORSTRING is the name of the operator to appear in error messages. */
tree
build_indirect_ref (tree ptr, const char *errorstring)
{
tree pointer = default_conversion (ptr);
tree type = TREE_TYPE (pointer);
if (TREE_CODE (type) == POINTER_TYPE)
{
if (TREE_CODE (pointer) == ADDR_EXPR
&& (TREE_TYPE (TREE_OPERAND (pointer, 0))
== TREE_TYPE (type)))
return TREE_OPERAND (pointer, 0);
else
{
tree t = TREE_TYPE (type);
tree ref;
ref = build1 (INDIRECT_REF, t, pointer);
if (!COMPLETE_OR_VOID_TYPE_P (t) && TREE_CODE (t) != ARRAY_TYPE)
{
error ("dereferencing pointer to incomplete type");
return error_mark_node;
}
if (VOID_TYPE_P (t) && skip_evaluation == 0)
warning (0, "dereferencing %<void *%> pointer");
/* We *must* set TREE_READONLY when dereferencing a pointer to const,
so that we get the proper error message if the result is used
to assign to. Also, &* is supposed to be a no-op.
And ANSI C seems to specify that the type of the result
should be the const type. */
/* A de-reference of a pointer to const is not a const. It is valid
to change it via some other pointer. */
TREE_READONLY (ref) = TYPE_READONLY (t);
TREE_SIDE_EFFECTS (ref)
= TYPE_VOLATILE (t) || TREE_SIDE_EFFECTS (pointer);
TREE_THIS_VOLATILE (ref) = TYPE_VOLATILE (t);
return ref;
}
}
else if (TREE_CODE (pointer) != ERROR_MARK)
error ("invalid type argument of %qs", errorstring);
return error_mark_node;
}
/* This handles expressions of the form "a[i]", which denotes
an array reference.
This is logically equivalent in C to *(a+i), but we may do it differently.
If A is a variable or a member, we generate a primitive ARRAY_REF.
This avoids forcing the array out of registers, and can work on
arrays that are not lvalues (for example, members of structures returned
by functions). */
tree
build_array_ref (tree array, tree index)
{
bool swapped = false;
if (TREE_TYPE (array) == error_mark_node
|| TREE_TYPE (index) == error_mark_node)
return error_mark_node;
if (TREE_CODE (TREE_TYPE (array)) != ARRAY_TYPE
&& TREE_CODE (TREE_TYPE (array)) != POINTER_TYPE)
{
tree temp;
if (TREE_CODE (TREE_TYPE (index)) != ARRAY_TYPE
&& TREE_CODE (TREE_TYPE (index)) != POINTER_TYPE)
{
error ("subscripted value is neither array nor pointer");
return error_mark_node;
}
temp = array;
array = index;
index = temp;
swapped = true;
}
if (!INTEGRAL_TYPE_P (TREE_TYPE (index)))
{
error ("array subscript is not an integer");
return error_mark_node;
}
if (TREE_CODE (TREE_TYPE (TREE_TYPE (array))) == FUNCTION_TYPE)
{
error ("subscripted value is pointer to function");
return error_mark_node;
}
/* ??? Existing practice has been to warn only when the char
index is syntactically the index, not for char[array]. */
if (!swapped)
warn_array_subscript_with_type_char (index);
/* Apply default promotions *after* noticing character types. */
index = default_conversion (index);
gcc_assert (TREE_CODE (TREE_TYPE (index)) == INTEGER_TYPE);
if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE)
{
tree rval, type;
/* An array that is indexed by a non-constant
cannot be stored in a register; we must be able to do
address arithmetic on its address.
Likewise an array of elements of variable size. */
if (TREE_CODE (index) != INTEGER_CST
|| (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array)))
&& TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array)))) != INTEGER_CST))
{
if (!c_mark_addressable (array))
return error_mark_node;
}
/* An array that is indexed by a constant value which is not within
the array bounds cannot be stored in a register either; because we
would get a crash in store_bit_field/extract_bit_field when trying
to access a non-existent part of the register. */
if (TREE_CODE (index) == INTEGER_CST
&& TYPE_DOMAIN (TREE_TYPE (array))
&& !int_fits_type_p (index, TYPE_DOMAIN (TREE_TYPE (array))))
{
if (!c_mark_addressable (array))
return error_mark_node;
}
if (pedantic)
{
tree foo = array;
while (TREE_CODE (foo) == COMPONENT_REF)
foo = TREE_OPERAND (foo, 0);
if (TREE_CODE (foo) == VAR_DECL && C_DECL_REGISTER (foo))
pedwarn ("ISO C forbids subscripting %<register%> array");
else if (!flag_isoc99 && !lvalue_p (foo))
pedwarn ("ISO C90 forbids subscripting non-lvalue array");
}
type = TREE_TYPE (TREE_TYPE (array));
if (TREE_CODE (type) != ARRAY_TYPE)
type = TYPE_MAIN_VARIANT (type);
rval = build4 (ARRAY_REF, type, array, index, NULL_TREE, NULL_TREE);
/* Array ref is const/volatile if the array elements are
or if the array is. */
TREE_READONLY (rval)
|= (TYPE_READONLY (TREE_TYPE (TREE_TYPE (array)))
| TREE_READONLY (array));
TREE_SIDE_EFFECTS (rval)
|= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array)))
| TREE_SIDE_EFFECTS (array));
TREE_THIS_VOLATILE (rval)
|= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array)))
/* This was added by rms on 16 Nov 91.
It fixes vol struct foo *a; a->elts[1]
in an inline function.
Hope it doesn't break something else. */
| TREE_THIS_VOLATILE (array));
return require_complete_type (fold (rval));
}
else
{
tree ar = default_conversion (array);
if (ar == error_mark_node)
return ar;
gcc_assert (TREE_CODE (TREE_TYPE (ar)) == POINTER_TYPE);
gcc_assert (TREE_CODE (TREE_TYPE (TREE_TYPE (ar))) != FUNCTION_TYPE);
return build_indirect_ref (build_binary_op (PLUS_EXPR, ar, index, 0),
"array indexing");
}
}
/* Build an external reference to identifier ID. FUN indicates
whether this will be used for a function call. LOC is the source
location of the identifier. */
tree
build_external_ref (tree id, int fun, location_t loc)
{
tree ref;
tree decl = lookup_name (id);
/* In Objective-C, an instance variable (ivar) may be preferred to
whatever lookup_name() found. */
decl = objc_lookup_ivar (decl, id);
if (decl && decl != error_mark_node)
ref = decl;
else if (fun)
/* Implicit function declaration. */
ref = implicitly_declare (id);
else if (decl == error_mark_node)
/* Don't complain about something that's already been
complained about. */
return error_mark_node;
else
{
undeclared_variable (id, loc);
return error_mark_node;
}
if (TREE_TYPE (ref) == error_mark_node)
return error_mark_node;
if (TREE_DEPRECATED (ref))
warn_deprecated_use (ref);
if (!skip_evaluation)
assemble_external (ref);
TREE_USED (ref) = 1;
if (TREE_CODE (ref) == FUNCTION_DECL && !in_alignof)
{
if (!in_sizeof && !in_typeof)
C_DECL_USED (ref) = 1;
else if (DECL_INITIAL (ref) == 0
&& DECL_EXTERNAL (ref)
&& !TREE_PUBLIC (ref))
record_maybe_used_decl (ref);
}
if (TREE_CODE (ref) == CONST_DECL)
{
used_types_insert (TREE_TYPE (ref));
ref = DECL_INITIAL (ref);
TREE_CONSTANT (ref) = 1;
TREE_INVARIANT (ref) = 1;
}
else if (current_function_decl != 0
&& !DECL_FILE_SCOPE_P (current_function_decl)
&& (TREE_CODE (ref) == VAR_DECL
|| TREE_CODE (ref) == PARM_DECL
|| TREE_CODE (ref) == FUNCTION_DECL))
{
tree context = decl_function_context (ref);
if (context != 0 && context != current_function_decl)
DECL_NONLOCAL (ref) = 1;
}
return ref;
}
/* Record details of decls possibly used inside sizeof or typeof. */
struct maybe_used_decl
{
/* The decl. */
tree decl;
/* The level seen at (in_sizeof + in_typeof). */
int level;
/* The next one at this level or above, or NULL. */
struct maybe_used_decl *next;
};
static struct maybe_used_decl *maybe_used_decls;
/* Record that DECL, an undefined static function reference seen
inside sizeof or typeof, might be used if the operand of sizeof is
a VLA type or the operand of typeof is a variably modified
type. */
static void
record_maybe_used_decl (tree decl)
{
struct maybe_used_decl *t = XOBNEW (&parser_obstack, struct maybe_used_decl);
t->decl = decl;
t->level = in_sizeof + in_typeof;
t->next = maybe_used_decls;
maybe_used_decls = t;
}
/* Pop the stack of decls possibly used inside sizeof or typeof. If
USED is false, just discard them. If it is true, mark them used
(if no longer inside sizeof or typeof) or move them to the next
level up (if still inside sizeof or typeof). */
void
pop_maybe_used (bool used)
{
struct maybe_used_decl *p = maybe_used_decls;
int cur_level = in_sizeof + in_typeof;
while (p && p->level > cur_level)
{
if (used)
{
if (cur_level == 0)
C_DECL_USED (p->decl) = 1;
else
p->level = cur_level;
}
p = p->next;
}
if (!used || cur_level == 0)
maybe_used_decls = p;
}
/* Return the result of sizeof applied to EXPR. */
struct c_expr
c_expr_sizeof_expr (struct c_expr expr)
{
struct c_expr ret;
if (expr.value == error_mark_node)
{
ret.value = error_mark_node;
ret.original_code = ERROR_MARK;
pop_maybe_used (false);
}
else
{
ret.value = c_sizeof (TREE_TYPE (expr.value));
ret.original_code = ERROR_MARK;
if (c_vla_type_p (TREE_TYPE (expr.value)))
{
/* sizeof is evaluated when given a vla (C99 6.5.3.4p2). */
ret.value = build2 (COMPOUND_EXPR, TREE_TYPE (ret.value), expr.value, ret.value);
}
pop_maybe_used (C_TYPE_VARIABLE_SIZE (TREE_TYPE (expr.value)));
}
return ret;
}
/* Return the result of sizeof applied to T, a structure for the type
name passed to sizeof (rather than the type itself). */
struct c_expr
c_expr_sizeof_type (struct c_type_name *t)
{
tree type;
struct c_expr ret;
type = groktypename (t);
ret.value = c_sizeof (type);
ret.original_code = ERROR_MARK;
pop_maybe_used (type != error_mark_node
? C_TYPE_VARIABLE_SIZE (type) : false);
return ret;
}
/* Build a function call to function FUNCTION with parameters PARAMS.
PARAMS is a list--a chain of TREE_LIST nodes--in which the
TREE_VALUE of each node is a parameter-expression.
FUNCTION's data type may be a function type or a pointer-to-function. */
tree
build_function_call (tree function, tree params)
{
tree fntype, fundecl = 0;
tree coerced_params;
tree name = NULL_TREE, result;
tree tem;
/* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */
STRIP_TYPE_NOPS (function);
/* Convert anything with function type to a pointer-to-function. */
if (TREE_CODE (function) == FUNCTION_DECL)
{
/* Implement type-directed function overloading for builtins.
resolve_overloaded_builtin and targetm.resolve_overloaded_builtin
handle all the type checking. The result is a complete expression
that implements this function call. */
tem = resolve_overloaded_builtin (function, params);
if (tem)
return tem;
name = DECL_NAME (function);
fundecl = function;
}
if (TREE_CODE (TREE_TYPE (function)) == FUNCTION_TYPE)
function = function_to_pointer_conversion (function);
/* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF
expressions, like those used for ObjC messenger dispatches. */
function = objc_rewrite_function_call (function, params);
fntype = TREE_TYPE (function);
if (TREE_CODE (fntype) == ERROR_MARK)
return error_mark_node;
if (!(TREE_CODE (fntype) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (fntype)) == FUNCTION_TYPE))
{
error ("called object %qE is not a function", function);
return error_mark_node;
}
if (fundecl && TREE_THIS_VOLATILE (fundecl))
current_function_returns_abnormally = 1;
/* fntype now gets the type of function pointed to. */
fntype = TREE_TYPE (fntype);
/* Check that the function is called through a compatible prototype.
If it is not, replace the call by a trap, wrapped up in a compound
expression if necessary. This has the nice side-effect to prevent
the tree-inliner from generating invalid assignment trees which may
blow up in the RTL expander later. */
if ((TREE_CODE (function) == NOP_EXPR
|| TREE_CODE (function) == CONVERT_EXPR)
&& TREE_CODE (tem = TREE_OPERAND (function, 0)) == ADDR_EXPR
&& TREE_CODE (tem = TREE_OPERAND (tem, 0)) == FUNCTION_DECL
&& !comptypes (fntype, TREE_TYPE (tem)))
{
tree return_type = TREE_TYPE (fntype);
tree trap = build_function_call (built_in_decls[BUILT_IN_TRAP],
NULL_TREE);
/* This situation leads to run-time undefined behavior. We can't,
therefore, simply error unless we can prove that all possible
executions of the program must execute the code. */
warning (0, "function called through a non-compatible type");
/* We can, however, treat "undefined" any way we please.
Call abort to encourage the user to fix the program. */
inform ("if this code is reached, the program will abort");
if (VOID_TYPE_P (return_type))
return trap;
else
{
tree rhs;
if (AGGREGATE_TYPE_P (return_type))
rhs = build_compound_literal (return_type,
build_constructor (return_type, 0));
else
rhs = fold_convert (return_type, integer_zero_node);
return build2 (COMPOUND_EXPR, return_type, trap, rhs);
}
}
/* Convert the parameters to the types declared in the
function prototype, or apply default promotions. */
coerced_params
= convert_arguments (TYPE_ARG_TYPES (fntype), params, function, fundecl);
if (coerced_params == error_mark_node)
return error_mark_node;
/* Check that the arguments to the function are valid. */
check_function_arguments (TYPE_ATTRIBUTES (fntype), coerced_params,
TYPE_ARG_TYPES (fntype));
if (require_constant_value)
{
result = fold_build3_initializer (CALL_EXPR, TREE_TYPE (fntype),
function, coerced_params, NULL_TREE);
if (TREE_CONSTANT (result)
&& (name == NULL_TREE
|| strncmp (IDENTIFIER_POINTER (name), "__builtin_", 10) != 0))
pedwarn_init ("initializer element is not constant");
}
else
result = fold_build3 (CALL_EXPR, TREE_TYPE (fntype),
function, coerced_params, NULL_TREE);
if (VOID_TYPE_P (TREE_TYPE (result)))
return result;
return require_complete_type (result);
}
/* Convert the argument expressions in the list VALUES
to the types in the list TYPELIST. The result is a list of converted
argument expressions, unless there are too few arguments in which
case it is error_mark_node.
If TYPELIST is exhausted, or when an element has NULL as its type,
perform the default conversions.
PARMLIST is the chain of parm decls for the function being called.
It may be 0, if that info is not available.
It is used only for generating error messages.
FUNCTION is a tree for the called function. It is used only for
error messages, where it is formatted with %qE.
This is also where warnings about wrong number of args are generated.
Both VALUES and the returned value are chains of TREE_LIST nodes
with the elements of the list in the TREE_VALUE slots of those nodes. */
static tree
convert_arguments (tree typelist, tree values, tree function, tree fundecl)
{
tree typetail, valtail;
tree result = NULL;
int parmnum;
tree selector;
/* Change pointer to function to the function itself for
diagnostics. */
if (TREE_CODE (function) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
function = TREE_OPERAND (function, 0);
/* Handle an ObjC selector specially for diagnostics. */
selector = objc_message_selector ();
/* Scan the given expressions and types, producing individual
converted arguments and pushing them on RESULT in reverse order. */
for (valtail = values, typetail = typelist, parmnum = 0;
valtail;
valtail = TREE_CHAIN (valtail), parmnum++)
{
tree type = typetail ? TREE_VALUE (typetail) : 0;
tree val = TREE_VALUE (valtail);
tree rname = function;
int argnum = parmnum + 1;
const char *invalid_func_diag;
if (type == void_type_node)
{
error ("too many arguments to function %qE", function);
break;
}
if (selector && argnum > 2)
{
rname = selector;
argnum -= 2;
}
STRIP_TYPE_NOPS (val);
val = require_complete_type (val);
if (type != 0)
{
/* Formal parm type is specified by a function prototype. */
tree parmval;
if (type == error_mark_node || !COMPLETE_TYPE_P (type))
{
error ("type of formal parameter %d is incomplete", parmnum + 1);
parmval = val;
}
else
{
/* Optionally warn about conversions that
differ from the default conversions. */
if (warn_conversion || warn_traditional)
{
unsigned int formal_prec = TYPE_PRECISION (type);
if (INTEGRAL_TYPE_P (type)
&& TREE_CODE (TREE_TYPE (val)) == REAL_TYPE)
warning (0, "passing argument %d of %qE as integer "
"rather than floating due to prototype",
argnum, rname);
if (INTEGRAL_TYPE_P (type)
&& TREE_CODE (TREE_TYPE (val)) == COMPLEX_TYPE)
warning (0, "passing argument %d of %qE as integer "
"rather than complex due to prototype",
argnum, rname);
else if (TREE_CODE (type) == COMPLEX_TYPE
&& TREE_CODE (TREE_TYPE (val)) == REAL_TYPE)
warning (0, "passing argument %d of %qE as complex "
"rather than floating due to prototype",
argnum, rname);
else if (TREE_CODE (type) == REAL_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (val)))
warning (0, "passing argument %d of %qE as floating "
"rather than integer due to prototype",
argnum, rname);
else if (TREE_CODE (type) == COMPLEX_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (val)))
warning (0, "passing argument %d of %qE as complex "
"rather than integer due to prototype",
argnum, rname);
else if (TREE_CODE (type) == REAL_TYPE
&& TREE_CODE (TREE_TYPE (val)) == COMPLEX_TYPE)
warning (0, "passing argument %d of %qE as floating "
"rather than complex due to prototype",
argnum, rname);
/* ??? At some point, messages should be written about
conversions between complex types, but that's too messy
to do now. */
else if (TREE_CODE (type) == REAL_TYPE
&& TREE_CODE (TREE_TYPE (val)) == REAL_TYPE)
{
/* Warn if any argument is passed as `float',
since without a prototype it would be `double'. */
if (formal_prec == TYPE_PRECISION (float_type_node)
&& type != dfloat32_type_node)
warning (0, "passing argument %d of %qE as %<float%> "
"rather than %<double%> due to prototype",
argnum, rname);
/* Warn if mismatch between argument and prototype
for decimal float types. Warn of conversions with
binary float types and of precision narrowing due to
prototype. */
else if (type != TREE_TYPE (val)
&& (type == dfloat32_type_node
|| type == dfloat64_type_node
|| type == dfloat128_type_node
|| TREE_TYPE (val) == dfloat32_type_node
|| TREE_TYPE (val) == dfloat64_type_node
|| TREE_TYPE (val) == dfloat128_type_node)
&& (formal_prec
<= TYPE_PRECISION (TREE_TYPE (val))
|| (type == dfloat128_type_node
&& (TREE_TYPE (val)
!= dfloat64_type_node
&& (TREE_TYPE (val)
!= dfloat32_type_node)))
|| (type == dfloat64_type_node
&& (TREE_TYPE (val)
!= dfloat32_type_node))))
warning (0, "passing argument %d of %qE as %qT "
"rather than %qT due to prototype",
argnum, rname, type, TREE_TYPE (val));
}
/* Detect integer changing in width or signedness.
These warnings are only activated with
-Wconversion, not with -Wtraditional. */
else if (warn_conversion && INTEGRAL_TYPE_P (type)
&& INTEGRAL_TYPE_P (TREE_TYPE (val)))
{
tree would_have_been = default_conversion (val);
tree type1 = TREE_TYPE (would_have_been);
if (TREE_CODE (type) == ENUMERAL_TYPE
&& (TYPE_MAIN_VARIANT (type)
== TYPE_MAIN_VARIANT (TREE_TYPE (val))))
/* No warning if function asks for enum
and the actual arg is that enum type. */
;
else if (formal_prec != TYPE_PRECISION (type1))
warning (OPT_Wconversion, "passing argument %d of %qE "
"with different width due to prototype",
argnum, rname);
else if (TYPE_UNSIGNED (type) == TYPE_UNSIGNED (type1))
;
/* Don't complain if the formal parameter type
is an enum, because we can't tell now whether
the value was an enum--even the same enum. */
else if (TREE_CODE (type) == ENUMERAL_TYPE)
;
else if (TREE_CODE (val) == INTEGER_CST
&& int_fits_type_p (val, type))
/* Change in signedness doesn't matter
if a constant value is unaffected. */
;
/* If the value is extended from a narrower
unsigned type, it doesn't matter whether we
pass it as signed or unsigned; the value
certainly is the same either way. */
else if (TYPE_PRECISION (TREE_TYPE (val)) < TYPE_PRECISION (type)
&& TYPE_UNSIGNED (TREE_TYPE (val)))
;
else if (TYPE_UNSIGNED (type))
warning (OPT_Wconversion, "passing argument %d of %qE "
"as unsigned due to prototype",
argnum, rname);
else
warning (OPT_Wconversion, "passing argument %d of %qE "
"as signed due to prototype", argnum, rname);
}
}
parmval = convert_for_assignment (type, val, ic_argpass,
fundecl, function,
parmnum + 1);
if (targetm.calls.promote_prototypes (fundecl ? TREE_TYPE (fundecl) : 0)
&& INTEGRAL_TYPE_P (type)
&& (TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node)))
parmval = default_conversion (parmval);
}
result = tree_cons (NULL_TREE, parmval, result);
}
else if (TREE_CODE (TREE_TYPE (val)) == REAL_TYPE
&& (TYPE_PRECISION (TREE_TYPE (val))
< TYPE_PRECISION (double_type_node))
&& !DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (val))))
/* Convert `float' to `double'. */
result = tree_cons (NULL_TREE, convert (double_type_node, val), result);
else if ((invalid_func_diag =
targetm.calls.invalid_arg_for_unprototyped_fn (typelist, fundecl, val)))
{
error (invalid_func_diag);
return error_mark_node;
}
else
/* Convert `short' and `char' to full-size `int'. */
result = tree_cons (NULL_TREE, default_conversion (val), result);
if (typetail)
typetail = TREE_CHAIN (typetail);
}
if (typetail != 0 && TREE_VALUE (typetail) != void_type_node)
{
error ("too few arguments to function %qE", function);
return error_mark_node;
}
return nreverse (result);
}
/* This is the entry point used by the parser to build unary operators
in the input. CODE, a tree_code, specifies the unary operator, and
ARG is the operand. For unary plus, the C parser currently uses
CONVERT_EXPR for code. */
struct c_expr
parser_build_unary_op (enum tree_code code, struct c_expr arg)
{
struct c_expr result;
result.original_code = ERROR_MARK;
result.value = build_unary_op (code, arg.value, 0);
overflow_warning (result.value);
return result;
}
/* This is the entry point used by the parser to build binary operators
in the input. CODE, a tree_code, specifies the binary operator, and
ARG1 and ARG2 are the operands. In addition to constructing the
expression, we check for operands that were written with other binary
operators in a way that is likely to confuse the user. */
struct c_expr
parser_build_binary_op (enum tree_code code, struct c_expr arg1,
struct c_expr arg2)
{
struct c_expr result;
enum tree_code code1 = arg1.original_code;
enum tree_code code2 = arg2.original_code;
result.value = build_binary_op (code, arg1.value, arg2.value, 1);
result.original_code = code;
if (TREE_CODE (result.value) == ERROR_MARK)
return result;
/* Check for cases such as x+y<<z which users are likely
to misinterpret. */
if (warn_parentheses)
{
if (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
{
if (code1 == PLUS_EXPR || code1 == MINUS_EXPR
|| code2 == PLUS_EXPR || code2 == MINUS_EXPR)
warning (OPT_Wparentheses,
"suggest parentheses around + or - inside shift");
}
if (code == TRUTH_ORIF_EXPR)
{
if (code1 == TRUTH_ANDIF_EXPR
|| code2 == TRUTH_ANDIF_EXPR)
warning (OPT_Wparentheses,
"suggest parentheses around && within ||");
}
if (code == BIT_IOR_EXPR)
{
if (code1 == BIT_AND_EXPR || code1 == BIT_XOR_EXPR
|| code1 == PLUS_EXPR || code1 == MINUS_EXPR
|| code2 == BIT_AND_EXPR || code2 == BIT_XOR_EXPR
|| code2 == PLUS_EXPR || code2 == MINUS_EXPR)
warning (OPT_Wparentheses,
"suggest parentheses around arithmetic in operand of |");
/* Check cases like x|y==z */
if (TREE_CODE_CLASS (code1) == tcc_comparison
|| TREE_CODE_CLASS (code2) == tcc_comparison)
warning (OPT_Wparentheses,
"suggest parentheses around comparison in operand of |");
}
if (code == BIT_XOR_EXPR)
{
if (code1 == BIT_AND_EXPR
|| code1 == PLUS_EXPR || code1 == MINUS_EXPR
|| code2 == BIT_AND_EXPR
|| code2 == PLUS_EXPR || code2 == MINUS_EXPR)
warning (OPT_Wparentheses,
"suggest parentheses around arithmetic in operand of ^");
/* Check cases like x^y==z */
if (TREE_CODE_CLASS (code1) == tcc_comparison
|| TREE_CODE_CLASS (code2) == tcc_comparison)
warning (OPT_Wparentheses,
"suggest parentheses around comparison in operand of ^");
}
if (code == BIT_AND_EXPR)
{
if (code1 == PLUS_EXPR || code1 == MINUS_EXPR
|| code2 == PLUS_EXPR || code2 == MINUS_EXPR)
warning (OPT_Wparentheses,
"suggest parentheses around + or - in operand of &");
/* Check cases like x&y==z */
if (TREE_CODE_CLASS (code1) == tcc_comparison
|| TREE_CODE_CLASS (code2) == tcc_comparison)
warning (OPT_Wparentheses,
"suggest parentheses around comparison in operand of &");
}
/* Similarly, check for cases like 1<=i<=10 that are probably errors. */
if (TREE_CODE_CLASS (code) == tcc_comparison
&& (TREE_CODE_CLASS (code1) == tcc_comparison
|| TREE_CODE_CLASS (code2) == tcc_comparison))
warning (OPT_Wparentheses, "comparisons like X<=Y<=Z do not "
"have their mathematical meaning");
}
/* Warn about comparisons against string literals, with the exception
of testing for equality or inequality of a string literal with NULL. */
if (code == EQ_EXPR || code == NE_EXPR)
{
if ((code1 == STRING_CST && !integer_zerop (arg2.value))
|| (code2 == STRING_CST && !integer_zerop (arg1.value)))
warning (OPT_Waddress,
"comparison with string literal results in unspecified behaviour");
}
else if (TREE_CODE_CLASS (code) == tcc_comparison
&& (code1 == STRING_CST || code2 == STRING_CST))
warning (OPT_Waddress,
"comparison with string literal results in unspecified behaviour");
overflow_warning (result.value);
return result;
}
/* Return a tree for the difference of pointers OP0 and OP1.
The resulting tree has type int. */
static tree
pointer_diff (tree op0, tree op1)
{
tree restype = ptrdiff_type_node;
tree target_type = TREE_TYPE (TREE_TYPE (op0));
tree con0, con1, lit0, lit1;
tree orig_op1 = op1;
if (pedantic || warn_pointer_arith)
{
if (TREE_CODE (target_type) == VOID_TYPE)
pedwarn ("pointer of type %<void *%> used in subtraction");
if (TREE_CODE (target_type) == FUNCTION_TYPE)
pedwarn ("pointer to a function used in subtraction");
}
/* If the conversion to ptrdiff_type does anything like widening or
converting a partial to an integral mode, we get a convert_expression
that is in the way to do any simplifications.
(fold-const.c doesn't know that the extra bits won't be needed.
split_tree uses STRIP_SIGN_NOPS, which leaves conversions to a
different mode in place.)
So first try to find a common term here 'by hand'; we want to cover
at least the cases that occur in legal static initializers. */
if ((TREE_CODE (op0) == NOP_EXPR || TREE_CODE (op0) == CONVERT_EXPR)
&& (TYPE_PRECISION (TREE_TYPE (op0))
== TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (op0, 0)))))
con0 = TREE_OPERAND (op0, 0);
else
con0 = op0;
if ((TREE_CODE (op1) == NOP_EXPR || TREE_CODE (op1) == CONVERT_EXPR)
&& (TYPE_PRECISION (TREE_TYPE (op1))
== TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (op1, 0)))))
con1 = TREE_OPERAND (op1, 0);
else
con1 = op1;
if (TREE_CODE (con0) == PLUS_EXPR)
{
lit0 = TREE_OPERAND (con0, 1);
con0 = TREE_OPERAND (con0, 0);
}
else
lit0 = integer_zero_node;
if (TREE_CODE (con1) == PLUS_EXPR)
{
lit1 = TREE_OPERAND (con1, 1);
con1 = TREE_OPERAND (con1, 0);
}
else
lit1 = integer_zero_node;
if (operand_equal_p (con0, con1, 0))
{
op0 = lit0;
op1 = lit1;
}
/* First do the subtraction as integers;
then drop through to build the divide operator.
Do not do default conversions on the minus operator
in case restype is a short type. */
op0 = build_binary_op (MINUS_EXPR, convert (restype, op0),
convert (restype, op1), 0);
/* This generates an error if op1 is pointer to incomplete type. */
if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (TREE_TYPE (orig_op1))))
error ("arithmetic on pointer to an incomplete type");
/* This generates an error if op0 is pointer to incomplete type. */
op1 = c_size_in_bytes (target_type);
/* Divide by the size, in easiest possible way. */
return fold_build2 (EXACT_DIV_EXPR, restype, op0, convert (restype, op1));
}
/* Construct and perhaps optimize a tree representation
for a unary operation. CODE, a tree_code, specifies the operation
and XARG is the operand.
For any CODE other than ADDR_EXPR, FLAG nonzero suppresses
the default promotions (such as from short to int).
For ADDR_EXPR, the default promotions are not applied; FLAG nonzero
allows non-lvalues; this is only used to handle conversion of non-lvalue
arrays to pointers in C99. */
tree
build_unary_op (enum tree_code code, tree xarg, int flag)
{
/* No default_conversion here. It causes trouble for ADDR_EXPR. */
tree arg = xarg;
tree argtype = 0;
enum tree_code typecode;
tree val;
int noconvert = flag;
const char *invalid_op_diag;
if (code != ADDR_EXPR)
arg = require_complete_type (arg);
typecode = TREE_CODE (TREE_TYPE (arg));
if (typecode == ERROR_MARK)
return error_mark_node;
if (typecode == ENUMERAL_TYPE || typecode == BOOLEAN_TYPE)
typecode = INTEGER_TYPE;
if ((invalid_op_diag
= targetm.invalid_unary_op (code, TREE_TYPE (xarg))))
{
error (invalid_op_diag);
return error_mark_node;
}
switch (code)
{
case CONVERT_EXPR:
/* This is used for unary plus, because a CONVERT_EXPR
is enough to prevent anybody from looking inside for
associativity, but won't generate any code. */
if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE
|| typecode == COMPLEX_TYPE
|| typecode == VECTOR_TYPE))
{
error ("wrong type argument to unary plus");
return error_mark_node;
}
else if (!noconvert)
arg = default_conversion (arg);
arg = non_lvalue (arg);
break;
case NEGATE_EXPR:
if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE
|| typecode == COMPLEX_TYPE
|| typecode == VECTOR_TYPE))
{
error ("wrong type argument to unary minus");
return error_mark_node;
}
else if (!noconvert)
arg = default_conversion (arg);
break;
case BIT_NOT_EXPR:
if (typecode == INTEGER_TYPE || typecode == VECTOR_TYPE)
{
if (!noconvert)
arg = default_conversion (arg);
}
else if (typecode == COMPLEX_TYPE)
{
code = CONJ_EXPR;
if (pedantic)
pedwarn ("ISO C does not support %<~%> for complex conjugation");
if (!noconvert)
arg = default_conversion (arg);
}
else
{
error ("wrong type argument to bit-complement");
return error_mark_node;
}
break;
case ABS_EXPR:
if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE))
{
error ("wrong type argument to abs");
return error_mark_node;
}
else if (!noconvert)
arg = default_conversion (arg);
break;
case CONJ_EXPR:
/* Conjugating a real value is a no-op, but allow it anyway. */
if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE
|| typecode == COMPLEX_TYPE))
{
error ("wrong type argument to conjugation");
return error_mark_node;
}
else if (!noconvert)
arg = default_conversion (arg);
break;
case TRUTH_NOT_EXPR:
if (typecode != INTEGER_TYPE
&& typecode != REAL_TYPE && typecode != POINTER_TYPE
&& typecode != COMPLEX_TYPE)
{
error ("wrong type argument to unary exclamation mark");
return error_mark_node;
}
arg = c_objc_common_truthvalue_conversion (arg);
return invert_truthvalue (arg);
case REALPART_EXPR:
if (TREE_CODE (arg) == COMPLEX_CST)
return TREE_REALPART (arg);
else if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
return fold_build1 (REALPART_EXPR, TREE_TYPE (TREE_TYPE (arg)), arg);
else
return arg;
case IMAGPART_EXPR:
if (TREE_CODE (arg) == COMPLEX_CST)
return TREE_IMAGPART (arg);
else if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
return fold_build1 (IMAGPART_EXPR, TREE_TYPE (TREE_TYPE (arg)), arg);
else
return convert (TREE_TYPE (arg), integer_zero_node);
case PREINCREMENT_EXPR:
case POSTINCREMENT_EXPR:
case PREDECREMENT_EXPR:
case POSTDECREMENT_EXPR:
/* Increment or decrement the real part of the value,
and don't change the imaginary part. */
if (typecode == COMPLEX_TYPE)
{
tree real, imag;
if (pedantic)
pedwarn ("ISO C does not support %<++%> and %<--%>"
" on complex types");
arg = stabilize_reference (arg);
real = build_unary_op (REALPART_EXPR, arg, 1);
imag = build_unary_op (IMAGPART_EXPR, arg, 1);
return build2 (COMPLEX_EXPR, TREE_TYPE (arg),
build_unary_op (code, real, 1), imag);
}
/* Report invalid types. */
if (typecode != POINTER_TYPE
&& typecode != INTEGER_TYPE && typecode != REAL_TYPE)
{
if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
error ("wrong type argument to increment");
else
error ("wrong type argument to decrement");
return error_mark_node;
}
{
tree inc;
tree result_type = TREE_TYPE (arg);
arg = get_unwidened (arg, 0);
argtype = TREE_TYPE (arg);
/* Compute the increment. */
if (typecode == POINTER_TYPE)
{
/* If pointer target is an undefined struct,
we just cannot know how to do the arithmetic. */
if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (result_type)))
{
if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
error ("increment of pointer to unknown structure");
else
error ("decrement of pointer to unknown structure");
}
else if ((pedantic || warn_pointer_arith)
&& (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE
|| TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE))
{
if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
pedwarn ("wrong type argument to increment");
else
pedwarn ("wrong type argument to decrement");
}
inc = c_size_in_bytes (TREE_TYPE (result_type));
}
else
inc = integer_one_node;
inc = convert (argtype, inc);
/* Complain about anything else that is not a true lvalue. */
if (!lvalue_or_else (arg, ((code == PREINCREMENT_EXPR
|| code == POSTINCREMENT_EXPR)
? lv_increment
: lv_decrement)))
return error_mark_node;
/* Report a read-only lvalue. */
if (TREE_READONLY (arg))
{
readonly_error (arg,
((code == PREINCREMENT_EXPR
|| code == POSTINCREMENT_EXPR)
? lv_increment : lv_decrement));
return error_mark_node;
}
if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE)
val = boolean_increment (code, arg);
else
val = build2 (code, TREE_TYPE (arg), arg, inc);
TREE_SIDE_EFFECTS (val) = 1;
val = convert (result_type, val);
if (TREE_CODE (val) != code)
TREE_NO_WARNING (val) = 1;
return val;
}
case ADDR_EXPR:
/* Note that this operation never does default_conversion. */
/* Let &* cancel out to simplify resulting code. */
if (TREE_CODE (arg) == INDIRECT_REF)
{
/* Don't let this be an lvalue. */
if (lvalue_p (TREE_OPERAND (arg, 0)))
return non_lvalue (TREE_OPERAND (arg, 0));
return TREE_OPERAND (arg, 0);
}
/* For &x[y], return x+y */
if (TREE_CODE (arg) == ARRAY_REF)
{
tree op0 = TREE_OPERAND (arg, 0);
if (!c_mark_addressable (op0))
return error_mark_node;
return build_binary_op (PLUS_EXPR,
(TREE_CODE (TREE_TYPE (op0)) == ARRAY_TYPE
? array_to_pointer_conversion (op0)
: op0),
TREE_OPERAND (arg, 1), 1);
}
/* Anything not already handled and not a true memory reference
or a non-lvalue array is an error. */
else if (typecode != FUNCTION_TYPE && !flag
&& !lvalue_or_else (arg, lv_addressof))
return error_mark_node;
/* Ordinary case; arg is a COMPONENT_REF or a decl. */
argtype = TREE_TYPE (arg);
/* If the lvalue is const or volatile, merge that into the type
to which the address will point. Note that you can't get a
restricted pointer by taking the address of something, so we
only have to deal with `const' and `volatile' here. */
if ((DECL_P (arg) || REFERENCE_CLASS_P (arg))
&& (TREE_READONLY (arg) || TREE_THIS_VOLATILE (arg)))
argtype = c_build_type_variant (argtype,
TREE_READONLY (arg),
TREE_THIS_VOLATILE (arg));
if (!c_mark_addressable (arg))
return error_mark_node;
gcc_assert (TREE_CODE (arg) != COMPONENT_REF
|| !DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1)));
argtype = build_pointer_type (argtype);
/* ??? Cope with user tricks that amount to offsetof. Delete this
when we have proper support for integer constant expressions. */
val = get_base_address (arg);
if (val && TREE_CODE (val) == INDIRECT_REF
&& TREE_CONSTANT (TREE_OPERAND (val, 0)))
{
tree op0 = fold_convert (argtype, fold_offsetof (arg, val)), op1;
op1 = fold_convert (argtype, TREE_OPERAND (val, 0));
return fold_build2 (PLUS_EXPR, argtype, op0, op1);
}
val = build1 (ADDR_EXPR, argtype, arg);
return val;
default:
gcc_unreachable ();
}
if (argtype == 0)
argtype = TREE_TYPE (arg);
return require_constant_value ? fold_build1_initializer (code, argtype, arg)
: fold_build1 (code, argtype, arg);
}
/* Return nonzero if REF is an lvalue valid for this language.
Lvalues can be assigned, unless their type has TYPE_READONLY.
Lvalues can have their address taken, unless they have C_DECL_REGISTER. */
static int
lvalue_p (tree ref)
{
enum tree_code code = TREE_CODE (ref);
switch (code)
{
case REALPART_EXPR:
case IMAGPART_EXPR:
case COMPONENT_REF:
return lvalue_p (TREE_OPERAND (ref, 0));
case COMPOUND_LITERAL_EXPR:
case STRING_CST:
return 1;
case INDIRECT_REF:
case ARRAY_REF:
case VAR_DECL:
case PARM_DECL:
case RESULT_DECL:
case ERROR_MARK:
return (TREE_CODE (TREE_TYPE (ref)) != FUNCTION_TYPE
&& TREE_CODE (TREE_TYPE (ref)) != METHOD_TYPE);
case BIND_EXPR:
return TREE_CODE (TREE_TYPE (ref)) == ARRAY_TYPE;
default:
return 0;
}
}
/* Give an error for storing in something that is 'const'. */
static void
readonly_error (tree arg, enum lvalue_use use)
{
gcc_assert (use == lv_assign || use == lv_increment || use == lv_decrement
|| use == lv_asm);
/* Using this macro rather than (for example) arrays of messages
ensures that all the format strings are checked at compile
time. */
#define READONLY_MSG(A, I, D, AS) (use == lv_assign ? (A) \
: (use == lv_increment ? (I) \
: (use == lv_decrement ? (D) : (AS))))
if (TREE_CODE (arg) == COMPONENT_REF)
{
if (TYPE_READONLY (TREE_TYPE (TREE_OPERAND (arg, 0))))
readonly_error (TREE_OPERAND (arg, 0), use);
else
error (READONLY_MSG (G_("assignment of read-only member %qD"),
G_("increment of read-only member %qD"),
G_("decrement of read-only member %qD"),
G_("read-only member %qD used as %<asm%> output")),
TREE_OPERAND (arg, 1));
}
else if (TREE_CODE (arg) == VAR_DECL)
error (READONLY_MSG (G_("assignment of read-only variable %qD"),
G_("increment of read-only variable %qD"),
G_("decrement of read-only variable %qD"),
G_("read-only variable %qD used as %<asm%> output")),
arg);
else
error (READONLY_MSG (G_("assignment of read-only location"),
G_("increment of read-only location"),
G_("decrement of read-only location"),
G_("read-only location used as %<asm%> output")));
}
/* Return nonzero if REF is an lvalue valid for this language;
otherwise, print an error message and return zero. USE says
how the lvalue is being used and so selects the error message. */
static int
lvalue_or_else (tree ref, enum lvalue_use use)
{
int win = lvalue_p (ref);
if (!win)
lvalue_error (use);
return win;
}
/* Mark EXP saying that we need to be able to take the
address of it; it should not be allocated in a register.
Returns true if successful. */
bool
c_mark_addressable (tree exp)
{
tree x = exp;
while (1)
switch (TREE_CODE (x))
{
case COMPONENT_REF:
if (DECL_C_BIT_FIELD (TREE_OPERAND (x, 1)))
{
error
("cannot take address of bit-field %qD", TREE_OPERAND (x, 1));
return false;
}
/* ... fall through ... */
case ADDR_EXPR:
case ARRAY_REF:
case REALPART_EXPR:
case IMAGPART_EXPR:
x = TREE_OPERAND (x, 0);
break;
case COMPOUND_LITERAL_EXPR:
case CONSTRUCTOR:
TREE_ADDRESSABLE (x) = 1;
return true;
case VAR_DECL:
case CONST_DECL:
case PARM_DECL:
case RESULT_DECL:
if (C_DECL_REGISTER (x)
&& DECL_NONLOCAL (x))
{
if (TREE_PUBLIC (x) || TREE_STATIC (x) || DECL_EXTERNAL (x))
{
error
("global register variable %qD used in nested function", x);
return false;
}
pedwarn ("register variable %qD used in nested function", x);
}
else if (C_DECL_REGISTER (x))
{
if (TREE_PUBLIC (x) || TREE_STATIC (x) || DECL_EXTERNAL (x))
error ("address of global register variable %qD requested", x);
else
error ("address of register variable %qD requested", x);
return false;
}
/* drops in */
case FUNCTION_DECL:
TREE_ADDRESSABLE (x) = 1;
/* drops out */
default:
return true;
}
}
/* Build and return a conditional expression IFEXP ? OP1 : OP2. */
tree
build_conditional_expr (tree ifexp, tree op1, tree op2)
{
tree type1;
tree type2;
enum tree_code code1;
enum tree_code code2;
tree result_type = NULL;
tree orig_op1 = op1, orig_op2 = op2;
/* Promote both alternatives. */
if (TREE_CODE (TREE_TYPE (op1)) != VOID_TYPE)
op1 = default_conversion (op1);
if (TREE_CODE (TREE_TYPE (op2)) != VOID_TYPE)
op2 = default_conversion (op2);
if (TREE_CODE (ifexp) == ERROR_MARK
|| TREE_CODE (TREE_TYPE (op1)) == ERROR_MARK
|| TREE_CODE (TREE_TYPE (op2)) == ERROR_MARK)
return error_mark_node;
type1 = TREE_TYPE (op1);
code1 = TREE_CODE (type1);
type2 = TREE_TYPE (op2);
code2 = TREE_CODE (type2);
/* C90 does not permit non-lvalue arrays in conditional expressions.
In C99 they will be pointers by now. */
if (code1 == ARRAY_TYPE || code2 == ARRAY_TYPE)
{
error ("non-lvalue array in conditional expression");
return error_mark_node;
}
/* Quickly detect the usual case where op1 and op2 have the same type
after promotion. */
if (TYPE_MAIN_VARIANT (type1) == TYPE_MAIN_VARIANT (type2))
{
if (type1 == type2)
result_type = type1;
else
result_type = TYPE_MAIN_VARIANT (type1);
}
else if ((code1 == INTEGER_TYPE || code1 == REAL_TYPE
|| code1 == COMPLEX_TYPE)
&& (code2 == INTEGER_TYPE || code2 == REAL_TYPE
|| code2 == COMPLEX_TYPE))
{
result_type = c_common_type (type1, type2);
/* If -Wsign-compare, warn here if type1 and type2 have
different signedness. We'll promote the signed to unsigned
and later code won't know it used to be different.
Do this check on the original types, so that explicit casts
will be considered, but default promotions won't. */
if (warn_sign_compare && !skip_evaluation)
{
int unsigned_op1 = TYPE_UNSIGNED (TREE_TYPE (orig_op1));
int unsigned_op2 = TYPE_UNSIGNED (TREE_TYPE (orig_op2));
if (unsigned_op1 ^ unsigned_op2)
{
bool ovf;
/* Do not warn if the result type is signed, since the
signed type will only be chosen if it can represent
all the values of the unsigned type. */
if (!TYPE_UNSIGNED (result_type))
/* OK */;
/* Do not warn if the signed quantity is an unsuffixed
integer literal (or some static constant expression
involving such literals) and it is non-negative. */
else if ((unsigned_op2
&& tree_expr_nonnegative_warnv_p (op1, &ovf))
|| (unsigned_op1
&& tree_expr_nonnegative_warnv_p (op2, &ovf)))
/* OK */;
else
warning (0, "signed and unsigned type in conditional expression");
}
}
}
else if (code1 == VOID_TYPE || code2 == VOID_TYPE)
{
if (pedantic && (code1 != VOID_TYPE || code2 != VOID_TYPE))
pedwarn ("ISO C forbids conditional expr with only one void side");
result_type = void_type_node;
}
else if (code1 == POINTER_TYPE && code2 == POINTER_TYPE)
{
if (comp_target_types (type1, type2))
result_type = common_pointer_type (type1, type2);
else if (null_pointer_constant_p (orig_op1))
result_type = qualify_type (type2, type1);
else if (null_pointer_constant_p (orig_op2))
result_type = qualify_type (type1, type2);
else if (VOID_TYPE_P (TREE_TYPE (type1)))
{
if (pedantic && TREE_CODE (TREE_TYPE (type2)) == FUNCTION_TYPE)
pedwarn ("ISO C forbids conditional expr between "
"%<void *%> and function pointer");
result_type = build_pointer_type (qualify_type (TREE_TYPE (type1),
TREE_TYPE (type2)));
}
else if (VOID_TYPE_P (TREE_TYPE (type2)))
{
if (pedantic && TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE)
pedwarn ("ISO C forbids conditional expr between "
"%<void *%> and function pointer");
result_type = build_pointer_type (qualify_type (TREE_TYPE (type2),
TREE_TYPE (type1)));
}
else
{
pedwarn ("pointer type mismatch in conditional expression");
result_type = build_pointer_type (void_type_node);
}
}
else if (code1 == POINTER_TYPE && code2 == INTEGER_TYPE)
{
if (!null_pointer_constant_p (orig_op2))
pedwarn ("pointer/integer type mismatch in conditional expression");
else
{
op2 = null_pointer_node;
}
result_type = type1;
}
else if (code2 == POINTER_TYPE && code1 == INTEGER_TYPE)
{
if (!null_pointer_constant_p (orig_op1))
pedwarn ("pointer/integer type mismatch in conditional expression");
else
{
op1 = null_pointer_node;
}
result_type = type2;
}
if (!result_type)
{
if (flag_cond_mismatch)
result_type = void_type_node;
else
{
error ("type mismatch in conditional expression");
return error_mark_node;
}
}
/* Merge const and volatile flags of the incoming types. */
result_type
= build_type_variant (result_type,
TREE_READONLY (op1) || TREE_READONLY (op2),
TREE_THIS_VOLATILE (op1) || TREE_THIS_VOLATILE (op2));
if (result_type != TREE_TYPE (op1))
op1 = convert_and_check (result_type, op1);
if (result_type != TREE_TYPE (op2))
op2 = convert_and_check (result_type, op2);
return fold_build3 (COND_EXPR, result_type, ifexp, op1, op2);
}
/* Return a compound expression that performs two expressions and
returns the value of the second of them. */
tree
build_compound_expr (tree expr1, tree expr2)
{
if (!TREE_SIDE_EFFECTS (expr1))
{
/* The left-hand operand of a comma expression is like an expression
statement: with -Wextra or -Wunused, we should warn if it doesn't have
any side-effects, unless it was explicitly cast to (void). */
if (warn_unused_value)
{
if (VOID_TYPE_P (TREE_TYPE (expr1))
&& (TREE_CODE (expr1) == NOP_EXPR
|| TREE_CODE (expr1) == CONVERT_EXPR))
; /* (void) a, b */
else if (VOID_TYPE_P (TREE_TYPE (expr1))
&& TREE_CODE (expr1) == COMPOUND_EXPR
&& (TREE_CODE (TREE_OPERAND (expr1, 1)) == CONVERT_EXPR
|| TREE_CODE (TREE_OPERAND (expr1, 1)) == NOP_EXPR))
; /* (void) a, (void) b, c */
else
warning (0, "left-hand operand of comma expression has no effect");
}
}
/* With -Wunused, we should also warn if the left-hand operand does have
side-effects, but computes a value which is not used. For example, in
`foo() + bar(), baz()' the result of the `+' operator is not used,
so we should issue a warning. */
else if (warn_unused_value)
warn_if_unused_value (expr1, input_location);
if (expr2 == error_mark_node)
return error_mark_node;
return build2 (COMPOUND_EXPR, TREE_TYPE (expr2), expr1, expr2);
}
/* Build an expression representing a cast to type TYPE of expression EXPR. */
tree
build_c_cast (tree type, tree expr)
{
tree value = expr;
if (type == error_mark_node || expr == error_mark_node)
return error_mark_node;
/* The ObjC front-end uses TYPE_MAIN_VARIANT to tie together types differing
only in <protocol> qualifications. But when constructing cast expressions,
the protocols do matter and must be kept around. */
if (objc_is_object_ptr (type) && objc_is_object_ptr (TREE_TYPE (expr)))
return build1 (NOP_EXPR, type, expr);
type = TYPE_MAIN_VARIANT (type);
if (TREE_CODE (type) == ARRAY_TYPE)
{
error ("cast specifies array type");
return error_mark_node;
}
if (TREE_CODE (type) == FUNCTION_TYPE)
{
error ("cast specifies function type");
return error_mark_node;
}
if (!VOID_TYPE_P (type))
{
value = require_complete_type (value);
if (value == error_mark_node)
return error_mark_node;
}
if (type == TYPE_MAIN_VARIANT (TREE_TYPE (value)))
{
if (pedantic)
{
if (TREE_CODE (type) == RECORD_TYPE
|| TREE_CODE (type) == UNION_TYPE)
pedwarn ("ISO C forbids casting nonscalar to the same type");
}
}
else if (TREE_CODE (type) == UNION_TYPE)
{
tree field;
for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
if (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (field)),
TYPE_MAIN_VARIANT (TREE_TYPE (value))))
break;
if (field)
{
tree t;
if (pedantic)
pedwarn ("ISO C forbids casts to union type");
t = digest_init (type,
build_constructor_single (type, field, value),
true, 0);
TREE_CONSTANT (t) = TREE_CONSTANT (value);
TREE_INVARIANT (t) = TREE_INVARIANT (value);
return t;
}
error ("cast to union type from type not present in union");
return error_mark_node;
}
else
{
tree otype, ovalue;
if (type == void_type_node)
return build1 (CONVERT_EXPR, type, value);
otype = TREE_TYPE (value);
/* Optionally warn about potentially worrisome casts. */
if (warn_cast_qual
&& TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (otype) == POINTER_TYPE)
{
tree in_type = type;
tree in_otype = otype;
int added = 0;
int discarded = 0;
/* Check that the qualifiers on IN_TYPE are a superset of
the qualifiers of IN_OTYPE. The outermost level of
POINTER_TYPE nodes is uninteresting and we stop as soon
as we hit a non-POINTER_TYPE node on either type. */
do
{
in_otype = TREE_TYPE (in_otype);
in_type = TREE_TYPE (in_type);
/* GNU C allows cv-qualified function types. 'const'
means the function is very pure, 'volatile' means it
can't return. We need to warn when such qualifiers
are added, not when they're taken away. */
if (TREE_CODE (in_otype) == FUNCTION_TYPE
&& TREE_CODE (in_type) == FUNCTION_TYPE)
added |= (TYPE_QUALS (in_type) & ~TYPE_QUALS (in_otype));
else
discarded |= (TYPE_QUALS (in_otype) & ~TYPE_QUALS (in_type));
}
while (TREE_CODE (in_type) == POINTER_TYPE
&& TREE_CODE (in_otype) == POINTER_TYPE);
if (added)
warning (0, "cast adds new qualifiers to function type");
if (discarded)
/* There are qualifiers present in IN_OTYPE that are not
present in IN_TYPE. */
warning (0, "cast discards qualifiers from pointer target type");
}
/* Warn about possible alignment problems. */
if (STRICT_ALIGNMENT
&& TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (otype) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (otype)) != VOID_TYPE
&& TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE
/* Don't warn about opaque types, where the actual alignment
restriction is unknown. */
&& !((TREE_CODE (TREE_TYPE (otype)) == UNION_TYPE
|| TREE_CODE (TREE_TYPE (otype)) == RECORD_TYPE)
&& TYPE_MODE (TREE_TYPE (otype)) == VOIDmode)
&& TYPE_ALIGN (TREE_TYPE (type)) > TYPE_ALIGN (TREE_TYPE (otype)))
warning (OPT_Wcast_align,
"cast increases required alignment of target type");
if (TREE_CODE (type) == INTEGER_TYPE
&& TREE_CODE (otype) == POINTER_TYPE
&& TYPE_PRECISION (type) != TYPE_PRECISION (otype))
/* Unlike conversion of integers to pointers, where the
warning is disabled for converting constants because
of cases such as SIG_*, warn about converting constant
pointers to integers. In some cases it may cause unwanted
sign extension, and a warning is appropriate. */
warning (OPT_Wpointer_to_int_cast,
"cast from pointer to integer of different size");
if (TREE_CODE (value) == CALL_EXPR
&& TREE_CODE (type) != TREE_CODE (otype))
warning (OPT_Wbad_function_cast, "cast from function call of type %qT "
"to non-matching type %qT", otype, type);
if (TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (otype) == INTEGER_TYPE
&& TYPE_PRECISION (type) != TYPE_PRECISION (otype)
/* Don't warn about converting any constant. */
&& !TREE_CONSTANT (value))
warning (OPT_Wint_to_pointer_cast, "cast to pointer from integer "
"of different size");
strict_aliasing_warning (otype, type, expr);
/* If pedantic, warn for conversions between function and object
pointer types, except for converting a null pointer constant
to function pointer type. */
if (pedantic
&& TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (otype) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (otype)) == FUNCTION_TYPE
&& TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE)
pedwarn ("ISO C forbids conversion of function pointer to object pointer type");
if (pedantic
&& TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (otype) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE
&& TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE
&& !null_pointer_constant_p (value))
pedwarn ("ISO C forbids conversion of object pointer to function pointer type");
ovalue = value;
value = convert (type, value);
/* Ignore any integer overflow caused by the cast. */
if (TREE_CODE (value) == INTEGER_CST)
{
if (CONSTANT_CLASS_P (ovalue)
&& (TREE_OVERFLOW (ovalue) || TREE_CONSTANT_OVERFLOW (ovalue)))
{
/* Avoid clobbering a shared constant. */
value = copy_node (value);
TREE_OVERFLOW (value) = TREE_OVERFLOW (ovalue);
TREE_CONSTANT_OVERFLOW (value) = TREE_CONSTANT_OVERFLOW (ovalue);
}
else if (TREE_OVERFLOW (value) || TREE_CONSTANT_OVERFLOW (value))
/* Reset VALUE's overflow flags, ensuring constant sharing. */
value = build_int_cst_wide (TREE_TYPE (value),
TREE_INT_CST_LOW (value),
TREE_INT_CST_HIGH (value));
}
}
/* Don't let a cast be an lvalue. */
if (value == expr)
value = non_lvalue (value);
return value;
}
/* Interpret a cast of expression EXPR to type TYPE. */
tree
c_cast_expr (struct c_type_name *type_name, tree expr)
{
tree type;
int saved_wsp = warn_strict_prototypes;
/* This avoids warnings about unprototyped casts on
integers. E.g. "#define SIG_DFL (void(*)())0". */
if (TREE_CODE (expr) == INTEGER_CST)
warn_strict_prototypes = 0;
type = groktypename (type_name);
warn_strict_prototypes = saved_wsp;
return build_c_cast (type, expr);
}
/* Build an assignment expression of lvalue LHS from value RHS.
MODIFYCODE is the code for a binary operator that we use
to combine the old value of LHS with RHS to get the new value.
Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment. */
tree
build_modify_expr (tree lhs, enum tree_code modifycode, tree rhs)
{
tree result;
tree newrhs;
tree lhstype = TREE_TYPE (lhs);
tree olhstype = lhstype;
/* Types that aren't fully specified cannot be used in assignments. */
lhs = require_complete_type (lhs);
/* Avoid duplicate error messages from operands that had errors. */
if (TREE_CODE (lhs) == ERROR_MARK || TREE_CODE (rhs) == ERROR_MARK)
return error_mark_node;
if (!lvalue_or_else (lhs, lv_assign))
return error_mark_node;
STRIP_TYPE_NOPS (rhs);
newrhs = rhs;
/* If a binary op has been requested, combine the old LHS value with the RHS
producing the value we should actually store into the LHS. */
if (modifycode != NOP_EXPR)
{
lhs = stabilize_reference (lhs);
newrhs = build_binary_op (modifycode, lhs, rhs, 1);
}
/* Give an error for storing in something that is 'const'. */
if (TREE_READONLY (lhs) || TYPE_READONLY (lhstype)
|| ((TREE_CODE (lhstype) == RECORD_TYPE
|| TREE_CODE (lhstype) == UNION_TYPE)
&& C_TYPE_FIELDS_READONLY (lhstype)))
{
readonly_error (lhs, lv_assign);
return error_mark_node;
}
/* If storing into a structure or union member,
it has probably been given type `int'.
Compute the type that would go with
the actual amount of storage the member occupies. */
if (TREE_CODE (lhs) == COMPONENT_REF
&& (TREE_CODE (lhstype) == INTEGER_TYPE
|| TREE_CODE (lhstype) == BOOLEAN_TYPE
|| TREE_CODE (lhstype) == REAL_TYPE
|| TREE_CODE (lhstype) == ENUMERAL_TYPE))
lhstype = TREE_TYPE (get_unwidened (lhs, 0));
/* If storing in a field that is in actuality a short or narrower than one,
we must store in the field in its actual type. */
if (lhstype != TREE_TYPE (lhs))
{
lhs = copy_node (lhs);
TREE_TYPE (lhs) = lhstype;
}
/* Convert new value to destination type. */
newrhs = convert_for_assignment (lhstype, newrhs, ic_assign,
NULL_TREE, NULL_TREE, 0);
if (TREE_CODE (newrhs) == ERROR_MARK)
return error_mark_node;
/* Emit ObjC write barrier, if necessary. */
if (c_dialect_objc () && flag_objc_gc)
{
result = objc_generate_write_barrier (lhs, modifycode, newrhs);
if (result)
return result;
}
/* Scan operands. */
result = build2 (MODIFY_EXPR, lhstype, lhs, newrhs);
TREE_SIDE_EFFECTS (result) = 1;
/* If we got the LHS in a different type for storing in,
convert the result back to the nominal type of LHS
so that the value we return always has the same type
as the LHS argument. */
if (olhstype == TREE_TYPE (result))
return result;
return convert_for_assignment (olhstype, result, ic_assign,
NULL_TREE, NULL_TREE, 0);
}
/* Convert value RHS to type TYPE as preparation for an assignment
to an lvalue of type TYPE.
The real work of conversion is done by `convert'.
The purpose of this function is to generate error messages
for assignments that are not allowed in C.
ERRTYPE says whether it is argument passing, assignment,
initialization or return.
FUNCTION is a tree for the function being called.
PARMNUM is the number of the argument, for printing in error messages. */
static tree
convert_for_assignment (tree type, tree rhs, enum impl_conv errtype,
tree fundecl, tree function, int parmnum)
{
enum tree_code codel = TREE_CODE (type);
tree rhstype;
enum tree_code coder;
tree rname = NULL_TREE;
bool objc_ok = false;
if (errtype == ic_argpass || errtype == ic_argpass_nonproto)
{
tree selector;
/* Change pointer to function to the function itself for
diagnostics. */
if (TREE_CODE (function) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
function = TREE_OPERAND (function, 0);
/* Handle an ObjC selector specially for diagnostics. */
selector = objc_message_selector ();
rname = function;
if (selector && parmnum > 2)
{
rname = selector;
parmnum -= 2;
}
}
/* This macro is used to emit diagnostics to ensure that all format
strings are complete sentences, visible to gettext and checked at
compile time. */
#define WARN_FOR_ASSIGNMENT(AR, AS, IN, RE) \
do { \
switch (errtype) \
{ \
case ic_argpass: \
pedwarn (AR, parmnum, rname); \
break; \
case ic_argpass_nonproto: \
warning (0, AR, parmnum, rname); \
break; \
case ic_assign: \
pedwarn (AS); \
break; \
case ic_init: \
pedwarn (IN); \
break; \
case ic_return: \
pedwarn (RE); \
break; \
default: \
gcc_unreachable (); \
} \
} while (0)
STRIP_TYPE_NOPS (rhs);
if (optimize && TREE_CODE (rhs) == VAR_DECL
&& TREE_CODE (TREE_TYPE (rhs)) != ARRAY_TYPE)
rhs = decl_constant_value_for_broken_optimization (rhs);
rhstype = TREE_TYPE (rhs);
coder = TREE_CODE (rhstype);
if (coder == ERROR_MARK)
return error_mark_node;
if (c_dialect_objc ())
{
int parmno;
switch (errtype)
{
case ic_return:
parmno = 0;
break;
case ic_assign:
parmno = -1;
break;
case ic_init:
parmno = -2;
break;
default:
parmno = parmnum;
break;
}
objc_ok = objc_compare_types (type, rhstype, parmno, rname);
}
if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (rhstype))
{
overflow_warning (rhs);
return rhs;
}
if (coder == VOID_TYPE)
{
/* Except for passing an argument to an unprototyped function,
this is a constraint violation. When passing an argument to
an unprototyped function, it is compile-time undefined;
making it a constraint in that case was rejected in
DR#252. */
error ("void value not ignored as it ought to be");
return error_mark_node;
}
rhs = require_complete_type (rhs);
if (rhs == error_mark_node)
return error_mark_node;
/* A type converts to a reference to it.
This code doesn't fully support references, it's just for the
special case of va_start and va_copy. */
if (codel == REFERENCE_TYPE
&& comptypes (TREE_TYPE (type), TREE_TYPE (rhs)) == 1)
{
if (!lvalue_p (rhs))
{
error ("cannot pass rvalue to reference parameter");
return error_mark_node;
}
if (!c_mark_addressable (rhs))
return error_mark_node;
rhs = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (rhs)), rhs);
/* We already know that these two types are compatible, but they
may not be exactly identical. In fact, `TREE_TYPE (type)' is
likely to be __builtin_va_list and `TREE_TYPE (rhs)' is
likely to be va_list, a typedef to __builtin_va_list, which
is different enough that it will cause problems later. */
if (TREE_TYPE (TREE_TYPE (rhs)) != TREE_TYPE (type))
rhs = build1 (NOP_EXPR, build_pointer_type (TREE_TYPE (type)), rhs);
rhs = build1 (NOP_EXPR, type, rhs);
return rhs;
}
/* Some types can interconvert without explicit casts. */
else if (codel == VECTOR_TYPE && coder == VECTOR_TYPE
&& vector_types_convertible_p (type, TREE_TYPE (rhs)))
return convert (type, rhs);
/* Arithmetic types all interconvert, and enum is treated like int. */
else if ((codel == INTEGER_TYPE || codel == REAL_TYPE
|| codel == ENUMERAL_TYPE || codel == COMPLEX_TYPE
|| codel == BOOLEAN_TYPE)
&& (coder == INTEGER_TYPE || coder == REAL_TYPE
|| coder == ENUMERAL_TYPE || coder == COMPLEX_TYPE
|| coder == BOOLEAN_TYPE))
return convert_and_check (type, rhs);
/* Aggregates in different TUs might need conversion. */
if ((codel == RECORD_TYPE || codel == UNION_TYPE)
&& codel == coder
&& comptypes (type, rhstype))
return convert_and_check (type, rhs);
/* Conversion to a transparent union from its member types.
This applies only to function arguments. */
if (codel == UNION_TYPE && TYPE_TRANSPARENT_UNION (type)
&& (errtype == ic_argpass || errtype == ic_argpass_nonproto))
{
tree memb, marginal_memb = NULL_TREE;
for (memb = TYPE_FIELDS (type); memb ; memb = TREE_CHAIN (memb))
{
tree memb_type = TREE_TYPE (memb);
if (comptypes (TYPE_MAIN_VARIANT (memb_type),
TYPE_MAIN_VARIANT (rhstype)))
break;
if (TREE_CODE (memb_type) != POINTER_TYPE)
continue;
if (coder == POINTER_TYPE)
{
tree ttl = TREE_TYPE (memb_type);
tree ttr = TREE_TYPE (rhstype);
/* Any non-function converts to a [const][volatile] void *
and vice versa; otherwise, targets must be the same.
Meanwhile, the lhs target must have all the qualifiers of
the rhs. */
if (VOID_TYPE_P (ttl) || VOID_TYPE_P (ttr)
|| comp_target_types (memb_type, rhstype))
{
/* If this type won't generate any warnings, use it. */
if (TYPE_QUALS (ttl) == TYPE_QUALS (ttr)
|| ((TREE_CODE (ttr) == FUNCTION_TYPE
&& TREE_CODE (ttl) == FUNCTION_TYPE)
? ((TYPE_QUALS (ttl) | TYPE_QUALS (ttr))
== TYPE_QUALS (ttr))
: ((TYPE_QUALS (ttl) | TYPE_QUALS (ttr))
== TYPE_QUALS (ttl))))
break;
/* Keep looking for a better type, but remember this one. */
if (!marginal_memb)
marginal_memb = memb;
}
}
/* Can convert integer zero to any pointer type. */
if (null_pointer_constant_p (rhs))
{
rhs = null_pointer_node;
break;
}
}
if (memb || marginal_memb)
{
if (!memb)
{
/* We have only a marginally acceptable member type;
it needs a warning. */
tree ttl = TREE_TYPE (TREE_TYPE (marginal_memb));
tree ttr = TREE_TYPE (rhstype);
/* Const and volatile mean something different for function
types, so the usual warnings are not appropriate. */
if (TREE_CODE (ttr) == FUNCTION_TYPE
&& TREE_CODE (ttl) == FUNCTION_TYPE)
{
/* Because const and volatile on functions are
restrictions that say the function will not do
certain things, it is okay to use a const or volatile
function where an ordinary one is wanted, but not
vice-versa. */
if (TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr))
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE "
"makes qualified function "
"pointer from unqualified"),
G_("assignment makes qualified "
"function pointer from "
"unqualified"),
G_("initialization makes qualified "
"function pointer from "
"unqualified"),
G_("return makes qualified function "
"pointer from unqualified"));
}
else if (TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl))
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE discards "
"qualifiers from pointer target type"),
G_("assignment discards qualifiers "
"from pointer target type"),
G_("initialization discards qualifiers "
"from pointer target type"),
G_("return discards qualifiers from "
"pointer target type"));
memb = marginal_memb;
}
if (pedantic && (!fundecl || !DECL_IN_SYSTEM_HEADER (fundecl)))
pedwarn ("ISO C prohibits argument conversion to union type");
return build_constructor_single (type, memb, rhs);
}
}
/* Conversions among pointers */
else if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
&& (coder == codel))
{
tree ttl = TREE_TYPE (type);
tree ttr = TREE_TYPE (rhstype);
tree mvl = ttl;
tree mvr = ttr;
bool is_opaque_pointer;
int target_cmp = 0; /* Cache comp_target_types () result. */
if (TREE_CODE (mvl) != ARRAY_TYPE)
mvl = TYPE_MAIN_VARIANT (mvl);
if (TREE_CODE (mvr) != ARRAY_TYPE)
mvr = TYPE_MAIN_VARIANT (mvr);
/* Opaque pointers are treated like void pointers. */
is_opaque_pointer = (targetm.vector_opaque_p (type)
|| targetm.vector_opaque_p (rhstype))
&& TREE_CODE (ttl) == VECTOR_TYPE
&& TREE_CODE (ttr) == VECTOR_TYPE;
/* C++ does not allow the implicit conversion void* -> T*. However,
for the purpose of reducing the number of false positives, we
tolerate the special case of
int *p = NULL;
where NULL is typically defined in C to be '(void *) 0'. */
if (VOID_TYPE_P (ttr) && rhs != null_pointer_node && !VOID_TYPE_P (ttl))
warning (OPT_Wc___compat, "request for implicit conversion from "
"%qT to %qT not permitted in C++", rhstype, type);
/* Check if the right-hand side has a format attribute but the
left-hand side doesn't. */
if (warn_missing_format_attribute
&& check_missing_format_attribute (type, rhstype))
{
switch (errtype)
{
case ic_argpass:
case ic_argpass_nonproto:
warning (OPT_Wmissing_format_attribute,
"argument %d of %qE might be "
"a candidate for a format attribute",
parmnum, rname);
break;
case ic_assign:
warning (OPT_Wmissing_format_attribute,
"assignment left-hand side might be "
"a candidate for a format attribute");
break;
case ic_init:
warning (OPT_Wmissing_format_attribute,
"initialization left-hand side might be "
"a candidate for a format attribute");
break;
case ic_return:
warning (OPT_Wmissing_format_attribute,
"return type might be "
"a candidate for a format attribute");
break;
default:
gcc_unreachable ();
}
}
/* Any non-function converts to a [const][volatile] void *
and vice versa; otherwise, targets must be the same.
Meanwhile, the lhs target must have all the qualifiers of the rhs. */
if (VOID_TYPE_P (ttl) || VOID_TYPE_P (ttr)
|| (target_cmp = comp_target_types (type, rhstype))
|| is_opaque_pointer
|| (c_common_unsigned_type (mvl)
== c_common_unsigned_type (mvr)))
{
if (pedantic
&& ((VOID_TYPE_P (ttl) && TREE_CODE (ttr) == FUNCTION_TYPE)
||
(VOID_TYPE_P (ttr)
&& !null_pointer_constant_p (rhs)
&& TREE_CODE (ttl) == FUNCTION_TYPE)))
WARN_FOR_ASSIGNMENT (G_("ISO C forbids passing argument %d of "
"%qE between function pointer "
"and %<void *%>"),
G_("ISO C forbids assignment between "
"function pointer and %<void *%>"),
G_("ISO C forbids initialization between "
"function pointer and %<void *%>"),
G_("ISO C forbids return between function "
"pointer and %<void *%>"));
/* Const and volatile mean something different for function types,
so the usual warnings are not appropriate. */
else if (TREE_CODE (ttr) != FUNCTION_TYPE
&& TREE_CODE (ttl) != FUNCTION_TYPE)
{
if (TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl))
{
/* Types differing only by the presence of the 'volatile'
qualifier are acceptable if the 'volatile' has been added
in by the Objective-C EH machinery. */
if (!objc_type_quals_match (ttl, ttr))
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE discards "
"qualifiers from pointer target type"),
G_("assignment discards qualifiers "
"from pointer target type"),
G_("initialization discards qualifiers "
"from pointer target type"),
G_("return discards qualifiers from "
"pointer target type"));
}
/* If this is not a case of ignoring a mismatch in signedness,
no warning. */
else if (VOID_TYPE_P (ttl) || VOID_TYPE_P (ttr)
|| target_cmp)
;
/* If there is a mismatch, do warn. */
else if (warn_pointer_sign)
WARN_FOR_ASSIGNMENT (G_("pointer targets in passing argument "
"%d of %qE differ in signedness"),
G_("pointer targets in assignment "
"differ in signedness"),
G_("pointer targets in initialization "
"differ in signedness"),
G_("pointer targets in return differ "
"in signedness"));
}
else if (TREE_CODE (ttl) == FUNCTION_TYPE
&& TREE_CODE (ttr) == FUNCTION_TYPE)
{
/* Because const and volatile on functions are restrictions
that say the function will not do certain things,
it is okay to use a const or volatile function
where an ordinary one is wanted, but not vice-versa. */
if (TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr))
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE makes "
"qualified function pointer "
"from unqualified"),
G_("assignment makes qualified function "
"pointer from unqualified"),
G_("initialization makes qualified "
"function pointer from unqualified"),
G_("return makes qualified function "
"pointer from unqualified"));
}
}
else
/* Avoid warning about the volatile ObjC EH puts on decls. */
if (!objc_ok)
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE from "
"incompatible pointer type"),
G_("assignment from incompatible pointer type"),
G_("initialization from incompatible "
"pointer type"),
G_("return from incompatible pointer type"));
return convert (type, rhs);
}
else if (codel == POINTER_TYPE && coder == ARRAY_TYPE)
{
/* ??? This should not be an error when inlining calls to
unprototyped functions. */
error ("invalid use of non-lvalue array");
return error_mark_node;
}
else if (codel == POINTER_TYPE && coder == INTEGER_TYPE)
{
/* An explicit constant 0 can convert to a pointer,
or one that results from arithmetic, even including
a cast to integer type. */
if (!null_pointer_constant_p (rhs))
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE makes "
"pointer from integer without a cast"),
G_("assignment makes pointer from integer "
"without a cast"),
G_("initialization makes pointer from "
"integer without a cast"),
G_("return makes pointer from integer "
"without a cast"));
return convert (type, rhs);
}
else if (codel == INTEGER_TYPE && coder == POINTER_TYPE)
{
WARN_FOR_ASSIGNMENT (G_("passing argument %d of %qE makes integer "
"from pointer without a cast"),
G_("assignment makes integer from pointer "
"without a cast"),
G_("initialization makes integer from pointer "
"without a cast"),
G_("return makes integer from pointer "
"without a cast"));
return convert (type, rhs);
}
else if (codel == BOOLEAN_TYPE && coder == POINTER_TYPE)
return convert (type, rhs);
switch (errtype)
{
case ic_argpass:
case ic_argpass_nonproto:
/* ??? This should not be an error when inlining calls to
unprototyped functions. */
error ("incompatible type for argument %d of %qE", parmnum, rname);
break;
case ic_assign:
error ("incompatible types in assignment");
break;
case ic_init:
error ("incompatible types in initialization");
break;
case ic_return:
error ("incompatible types in return");
break;
default:
gcc_unreachable ();
}
return error_mark_node;
}
/* Convert VALUE for assignment into inlined parameter PARM. ARGNUM
is used for error and warning reporting and indicates which argument
is being processed. */
tree
c_convert_parm_for_inlining (tree parm, tree value, tree fn, int argnum)
{
tree ret, type;
/* If FN was prototyped at the call site, the value has been converted
already in convert_arguments.
However, we might see a prototype now that was not in place when
the function call was seen, so check that the VALUE actually matches
PARM before taking an early exit. */
if (!value
|| (TYPE_ARG_TYPES (TREE_TYPE (fn))
&& (TYPE_MAIN_VARIANT (TREE_TYPE (parm))
== TYPE_MAIN_VARIANT (TREE_TYPE (value)))))
return value;
type = TREE_TYPE (parm);
ret = convert_for_assignment (type, value,
ic_argpass_nonproto, fn,
fn, argnum);
if (targetm.calls.promote_prototypes (TREE_TYPE (fn))
&& INTEGRAL_TYPE_P (type)
&& (TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node)))
ret = default_conversion (ret);
return ret;
}
/* If VALUE is a compound expr all of whose expressions are constant, then
return its value. Otherwise, return error_mark_node.
This is for handling COMPOUND_EXPRs as initializer elements
which is allowed with a warning when -pedantic is specified. */
static tree
valid_compound_expr_initializer (tree value, tree endtype)
{
if (TREE_CODE (value) == COMPOUND_EXPR)
{
if (valid_compound_expr_initializer (TREE_OPERAND (value, 0), endtype)
== error_mark_node)
return error_mark_node;
return valid_compound_expr_initializer (TREE_OPERAND (value, 1),
endtype);
}
else if (!initializer_constant_valid_p (value, endtype))
return error_mark_node;
else
return value;
}
/* Perform appropriate conversions on the initial value of a variable,
store it in the declaration DECL,
and print any error messages that are appropriate.
If the init is invalid, store an ERROR_MARK. */
void
store_init_value (tree decl, tree init)
{
tree value, type;
/* If variable's type was invalidly declared, just ignore it. */
type = TREE_TYPE (decl);
if (TREE_CODE (type) == ERROR_MARK)
return;
/* Digest the specified initializer into an expression. */
value = digest_init (type, init, true, TREE_STATIC (decl));
/* Store the expression if valid; else report error. */
if (!in_system_header
&& AGGREGATE_TYPE_P (TREE_TYPE (decl)) && !TREE_STATIC (decl))
warning (OPT_Wtraditional, "traditional C rejects automatic "
"aggregate initialization");
DECL_INITIAL (decl) = value;
/* ANSI wants warnings about out-of-range constant initializers. */
STRIP_TYPE_NOPS (value);
constant_expression_warning (value);
/* Check if we need to set array size from compound literal size. */
if (TREE_CODE (type) == ARRAY_TYPE
&& TYPE_DOMAIN (type) == 0
&& value != error_mark_node)
{
tree inside_init = init;
STRIP_TYPE_NOPS (inside_init);
inside_init = fold (inside_init);
if (TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR)
{
tree cldecl = COMPOUND_LITERAL_EXPR_DECL (inside_init);
if (TYPE_DOMAIN (TREE_TYPE (cldecl)))
{
/* For int foo[] = (int [3]){1}; we need to set array size
now since later on array initializer will be just the
brace enclosed list of the compound literal. */
type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
TREE_TYPE (decl) = type;
TYPE_DOMAIN (type) = TYPE_DOMAIN (TREE_TYPE (cldecl));
layout_type (type);
layout_decl (cldecl, 0);
}
}
}
}
/* Methods for storing and printing names for error messages. */
/* Implement a spelling stack that allows components of a name to be pushed
and popped. Each element on the stack is this structure. */
struct spelling
{
int kind;
union
{
unsigned HOST_WIDE_INT i;
const char *s;
} u;
};
#define SPELLING_STRING 1
#define SPELLING_MEMBER 2
#define SPELLING_BOUNDS 3
static struct spelling *spelling; /* Next stack element (unused). */
static struct spelling *spelling_base; /* Spelling stack base. */
static int spelling_size; /* Size of the spelling stack. */
/* Macros to save and restore the spelling stack around push_... functions.
Alternative to SAVE_SPELLING_STACK. */
#define SPELLING_DEPTH() (spelling - spelling_base)
#define RESTORE_SPELLING_DEPTH(DEPTH) (spelling = spelling_base + (DEPTH))
/* Push an element on the spelling stack with type KIND and assign VALUE
to MEMBER. */
#define PUSH_SPELLING(KIND, VALUE, MEMBER) \
{ \
int depth = SPELLING_DEPTH (); \
\
if (depth >= spelling_size) \
{ \
spelling_size += 10; \
spelling_base = XRESIZEVEC (struct spelling, spelling_base, \
spelling_size); \
RESTORE_SPELLING_DEPTH (depth); \
} \
\
spelling->kind = (KIND); \
spelling->MEMBER = (VALUE); \
spelling++; \
}
/* Push STRING on the stack. Printed literally. */
static void
push_string (const char *string)
{
PUSH_SPELLING (SPELLING_STRING, string, u.s);
}
/* Push a member name on the stack. Printed as '.' STRING. */
static void
push_member_name (tree decl)
{
const char *const string
= DECL_NAME (decl) ? IDENTIFIER_POINTER (DECL_NAME (decl)) : "<anonymous>";
PUSH_SPELLING (SPELLING_MEMBER, string, u.s);
}
/* Push an array bounds on the stack. Printed as [BOUNDS]. */
static void
push_array_bounds (unsigned HOST_WIDE_INT bounds)
{
PUSH_SPELLING (SPELLING_BOUNDS, bounds, u.i);
}
/* Compute the maximum size in bytes of the printed spelling. */
static int
spelling_length (void)
{
int size = 0;
struct spelling *p;
for (p = spelling_base; p < spelling; p++)
{
if (p->kind == SPELLING_BOUNDS)
size += 25;
else
size += strlen (p->u.s) + 1;
}
return size;
}
/* Print the spelling to BUFFER and return it. */
static char *
print_spelling (char *buffer)
{
char *d = buffer;
struct spelling *p;
for (p = spelling_base; p < spelling; p++)
if (p->kind == SPELLING_BOUNDS)
{
sprintf (d, "[" HOST_WIDE_INT_PRINT_UNSIGNED "]", p->u.i);
d += strlen (d);
}
else
{
const char *s;
if (p->kind == SPELLING_MEMBER)
*d++ = '.';
for (s = p->u.s; (*d = *s++); d++)
;
}
*d++ = '\0';
return buffer;
}
/* Issue an error message for a bad initializer component.
MSGID identifies the message.
The component name is taken from the spelling stack. */
void
error_init (const char *msgid)
{
char *ofwhat;
error ("%s", _(msgid));
ofwhat = print_spelling ((char *) alloca (spelling_length () + 1));
if (*ofwhat)
error ("(near initialization for %qs)", ofwhat);
}
/* Issue a pedantic warning for a bad initializer component.
MSGID identifies the message.
The component name is taken from the spelling stack. */
void
pedwarn_init (const char *msgid)
{
char *ofwhat;
pedwarn ("%s", _(msgid));
ofwhat = print_spelling ((char *) alloca (spelling_length () + 1));
if (*ofwhat)
pedwarn ("(near initialization for %qs)", ofwhat);
}
/* Issue a warning for a bad initializer component.
MSGID identifies the message.
The component name is taken from the spelling stack. */
static void
warning_init (const char *msgid)
{
char *ofwhat;
warning (0, "%s", _(msgid));
ofwhat = print_spelling ((char *) alloca (spelling_length () + 1));
if (*ofwhat)
warning (0, "(near initialization for %qs)", ofwhat);
}
/* If TYPE is an array type and EXPR is a parenthesized string
constant, warn if pedantic that EXPR is being used to initialize an
object of type TYPE. */
void
maybe_warn_string_init (tree type, struct c_expr expr)
{
if (pedantic
&& TREE_CODE (type) == ARRAY_TYPE
&& TREE_CODE (expr.value) == STRING_CST
&& expr.original_code != STRING_CST)
pedwarn_init ("array initialized from parenthesized string constant");
}
/* Digest the parser output INIT as an initializer for type TYPE.
Return a C expression of type TYPE to represent the initial value.
If INIT is a string constant, STRICT_STRING is true if it is
unparenthesized or we should not warn here for it being parenthesized.
For other types of INIT, STRICT_STRING is not used.
REQUIRE_CONSTANT requests an error if non-constant initializers or
elements are seen. */
static tree
digest_init (tree type, tree init, bool strict_string, int require_constant)
{
enum tree_code code = TREE_CODE (type);
tree inside_init = init;
if (type == error_mark_node
|| !init
|| init == error_mark_node
|| TREE_TYPE (init) == error_mark_node)
return error_mark_node;
STRIP_TYPE_NOPS (inside_init);
inside_init = fold (inside_init);
/* Initialization of an array of chars from a string constant
optionally enclosed in braces. */
if (code == ARRAY_TYPE && inside_init
&& TREE_CODE (inside_init) == STRING_CST)
{
tree typ1 = TYPE_MAIN_VARIANT (TREE_TYPE (type));
/* Note that an array could be both an array of character type
and an array of wchar_t if wchar_t is signed char or unsigned
char. */
bool char_array = (typ1 == char_type_node
|| typ1 == signed_char_type_node
|| typ1 == unsigned_char_type_node);
bool wchar_array = !!comptypes (typ1, wchar_type_node);
if (char_array || wchar_array)
{
struct c_expr expr;
bool char_string;
expr.value = inside_init;
expr.original_code = (strict_string ? STRING_CST : ERROR_MARK);
maybe_warn_string_init (type, expr);
char_string
= (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (inside_init)))
== char_type_node);
if (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)),
TYPE_MAIN_VARIANT (type)))
return inside_init;
if (!wchar_array && !char_string)
{
error_init ("char-array initialized from wide string");
return error_mark_node;
}
if (char_string && !char_array)
{
error_init ("wchar_t-array initialized from non-wide string");
return error_mark_node;
}
TREE_TYPE (inside_init) = type;
if (TYPE_DOMAIN (type) != 0
&& TYPE_SIZE (type) != 0
&& TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
/* Subtract 1 (or sizeof (wchar_t))
because it's ok to ignore the terminating null char
that is counted in the length of the constant. */
&& 0 > compare_tree_int (TYPE_SIZE_UNIT (type),
TREE_STRING_LENGTH (inside_init)
- ((TYPE_PRECISION (typ1)
!= TYPE_PRECISION (char_type_node))
? (TYPE_PRECISION (wchar_type_node)
/ BITS_PER_UNIT)
: 1)))
pedwarn_init ("initializer-string for array of chars is too long");
return inside_init;
}
else if (INTEGRAL_TYPE_P (typ1))
{
error_init ("array of inappropriate type initialized "
"from string constant");
return error_mark_node;
}
}
/* Build a VECTOR_CST from a *constant* vector constructor. If the
vector constructor is not constant (e.g. {1,2,3,foo()}) then punt
below and handle as a constructor. */
if (code == VECTOR_TYPE
&& TREE_CODE (TREE_TYPE (inside_init)) == VECTOR_TYPE
&& vector_types_convertible_p (TREE_TYPE (inside_init), type)
&& TREE_CONSTANT (inside_init))
{
if (TREE_CODE (inside_init) == VECTOR_CST
&& comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)),
TYPE_MAIN_VARIANT (type)))
return inside_init;
if (TREE_CODE (inside_init) == CONSTRUCTOR)
{
unsigned HOST_WIDE_INT ix;
tree value;
bool constant_p = true;
/* Iterate through elements and check if all constructor
elements are *_CSTs. */
FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (inside_init), ix, value)
if (!CONSTANT_CLASS_P (value))
{
constant_p = false;
break;
}
if (constant_p)
return build_vector_from_ctor (type,
CONSTRUCTOR_ELTS (inside_init));
}
}
/* Any type can be initialized
from an expression of the same type, optionally with braces. */
if (inside_init && TREE_TYPE (inside_init) != 0
&& (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)),
TYPE_MAIN_VARIANT (type))
|| (code == ARRAY_TYPE
&& comptypes (TREE_TYPE (inside_init), type))
|| (code == VECTOR_TYPE
&& comptypes (TREE_TYPE (inside_init), type))
|| (code == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE
&& comptypes (TREE_TYPE (TREE_TYPE (inside_init)),
TREE_TYPE (type)))))
{
if (code == POINTER_TYPE)
{
if (TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE)
{
if (TREE_CODE (inside_init) == STRING_CST
|| TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR)
inside_init = array_to_pointer_conversion (inside_init);
else
{
error_init ("invalid use of non-lvalue array");
return error_mark_node;
}
}
}
if (code == VECTOR_TYPE)
/* Although the types are compatible, we may require a
conversion. */
inside_init = convert (type, inside_init);
if (require_constant
&& (code == VECTOR_TYPE || !flag_isoc99)
&& TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR)
{
/* As an extension, allow initializing objects with static storage
duration with compound literals (which are then treated just as
the brace enclosed list they contain). Also allow this for
vectors, as we can only assign them with compound literals. */
tree decl = COMPOUND_LITERAL_EXPR_DECL (inside_init);
inside_init = DECL_INITIAL (decl);
}
if (code == ARRAY_TYPE && TREE_CODE (inside_init) != STRING_CST
&& TREE_CODE (inside_init) != CONSTRUCTOR)
{
error_init ("array initialized from non-constant array expression");
return error_mark_node;
}
if (optimize && TREE_CODE (inside_init) == VAR_DECL)
inside_init = decl_constant_value_for_broken_optimization (inside_init);
/* Compound expressions can only occur here if -pedantic or
-pedantic-errors is specified. In the later case, we always want
an error. In the former case, we simply want a warning. */
if (require_constant && pedantic
&& TREE_CODE (inside_init) == COMPOUND_EXPR)
{
inside_init
= valid_compound_expr_initializer (inside_init,
TREE_TYPE (inside_init));
if (inside_init == error_mark_node)
error_init ("initializer element is not constant");
else
pedwarn_init ("initializer element is not constant");
if (flag_pedantic_errors)
inside_init = error_mark_node;
}
else if (require_constant
&& !initializer_constant_valid_p (inside_init,
TREE_TYPE (inside_init)))
{
error_init ("initializer element is not constant");
inside_init = error_mark_node;
}
/* Added to enable additional -Wmissing-format-attribute warnings. */
if (TREE_CODE (TREE_TYPE (inside_init)) == POINTER_TYPE)
inside_init = convert_for_assignment (type, inside_init, ic_init, NULL_TREE,
NULL_TREE, 0);
return inside_init;
}
/* Handle scalar types, including conversions. */
if (code == INTEGER_TYPE || code == REAL_TYPE || code == POINTER_TYPE
|| code == ENUMERAL_TYPE || code == BOOLEAN_TYPE || code == COMPLEX_TYPE
|| code == VECTOR_TYPE)
{
if (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE
&& (TREE_CODE (init) == STRING_CST
|| TREE_CODE (init) == COMPOUND_LITERAL_EXPR))
init = array_to_pointer_conversion (init);
inside_init
= convert_for_assignment (type, init, ic_init,
NULL_TREE, NULL_TREE, 0);
/* Check to see if we have already given an error message. */
if (inside_init == error_mark_node)
;
else if (require_constant && !TREE_CONSTANT (inside_init))
{
error_init ("initializer element is not constant");
inside_init = error_mark_node;
}
else if (require_constant
&& !initializer_constant_valid_p (inside_init,
TREE_TYPE (inside_init)))
{
error_init ("initializer element is not computable at load time");
inside_init = error_mark_node;
}
return inside_init;
}
/* Come here only for records and arrays. */
if (COMPLETE_TYPE_P (type) && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
{
error_init ("variable-sized object may not be initialized");
return error_mark_node;
}
error_init ("invalid initializer");
return error_mark_node;
}
/* Handle initializers that use braces. */
/* Type of object we are accumulating a constructor for.
This type is always a RECORD_TYPE, UNION_TYPE or ARRAY_TYPE. */
static tree constructor_type;
/* For a RECORD_TYPE or UNION_TYPE, this is the chain of fields
left to fill. */
static tree constructor_fields;
/* For an ARRAY_TYPE, this is the specified index
at which to store the next element we get. */
static tree constructor_index;
/* For an ARRAY_TYPE, this is the maximum index. */
static tree constructor_max_index;
/* For a RECORD_TYPE, this is the first field not yet written out. */
static tree constructor_unfilled_fields;
/* For an ARRAY_TYPE, this is the index of the first element
not yet written out. */
static tree constructor_unfilled_index;
/* In a RECORD_TYPE, the byte index of the next consecutive field.
This is so we can generate gaps between fields, when appropriate. */
static tree constructor_bit_index;
/* If we are saving up the elements rather than allocating them,
this is the list of elements so far (in reverse order,
most recent first). */
static VEC(constructor_elt,gc) *constructor_elements;
/* 1 if constructor should be incrementally stored into a constructor chain,
0 if all the elements should be kept in AVL tree. */
static int constructor_incremental;
/* 1 if so far this constructor's elements are all compile-time constants. */
static int constructor_constant;
/* 1 if so far this constructor's elements are all valid address constants. */
static int constructor_simple;
/* 1 if this constructor is erroneous so far. */
static int constructor_erroneous;
/* Structure for managing pending initializer elements, organized as an
AVL tree. */
struct init_node
{
struct init_node *left, *right;
struct init_node *parent;
int balance;
tree purpose;
tree value;
};
/* Tree of pending elements at this constructor level.
These are elements encountered out of order
which belong at places we haven't reached yet in actually
writing the output.
Will never hold tree nodes across GC runs. */
static struct init_node *constructor_pending_elts;
/* The SPELLING_DEPTH of this constructor. */
static int constructor_depth;
/* DECL node for which an initializer is being read.
0 means we are reading a constructor expression
such as (struct foo) {...}. */
static tree constructor_decl;
/* Nonzero if this is an initializer for a top-level decl. */
static int constructor_top_level;
/* Nonzero if there were any member designators in this initializer. */
static int constructor_designated;
/* Nesting depth of designator list. */
static int designator_depth;
/* Nonzero if there were diagnosed errors in this designator list. */
static int designator_erroneous;
/* This stack has a level for each implicit or explicit level of
structuring in the initializer, including the outermost one. It
saves the values of most of the variables above. */
struct constructor_range_stack;
struct constructor_stack
{
struct constructor_stack *next;
tree type;
tree fields;
tree index;
tree max_index;
tree unfilled_index;
tree unfilled_fields;
tree bit_index;
VEC(constructor_elt,gc) *elements;
struct init_node *pending_elts;
int offset;
int depth;
/* If value nonzero, this value should replace the entire
constructor at this level. */
struct c_expr replacement_value;
struct constructor_range_stack *range_stack;
char constant;
char simple;
char implicit;
char erroneous;
char outer;
char incremental;
char designated;
};
static struct constructor_stack *constructor_stack;
/* This stack represents designators from some range designator up to
the last designator in the list. */
struct constructor_range_stack
{
struct constructor_range_stack *next, *prev;
struct constructor_stack *stack;
tree range_start;
tree index;
tree range_end;
tree fields;
};
static struct constructor_range_stack *constructor_range_stack;
/* This stack records separate initializers that are nested.
Nested initializers can't happen in ANSI C, but GNU C allows them
in cases like { ... (struct foo) { ... } ... }. */
struct initializer_stack
{
struct initializer_stack *next;
tree decl;
struct constructor_stack *constructor_stack;
struct constructor_range_stack *constructor_range_stack;
VEC(constructor_elt,gc) *elements;
struct spelling *spelling;
struct spelling *spelling_base;
int spelling_size;
char top_level;
char require_constant_value;
char require_constant_elements;
};
static struct initializer_stack *initializer_stack;
/* Prepare to parse and output the initializer for variable DECL. */
void
start_init (tree decl, tree asmspec_tree ATTRIBUTE_UNUSED, int top_level)
{
const char *locus;
struct initializer_stack *p = XNEW (struct initializer_stack);
p->decl = constructor_decl;
p->require_constant_value = require_constant_value;
p->require_constant_elements = require_constant_elements;
p->constructor_stack = constructor_stack;
p->constructor_range_stack = constructor_range_stack;
p->elements = constructor_elements;
p->spelling = spelling;
p->spelling_base = spelling_base;
p->spelling_size = spelling_size;
p->top_level = constructor_top_level;
p->next = initializer_stack;
initializer_stack = p;
constructor_decl = decl;
constructor_designated = 0;
constructor_top_level = top_level;
if (decl != 0 && decl != error_mark_node)
{
require_constant_value = TREE_STATIC (decl);
require_constant_elements
= ((TREE_STATIC (decl) || (pedantic && !flag_isoc99))
/* For a scalar, you can always use any value to initialize,
even within braces. */
&& (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
|| TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
|| TREE_CODE (TREE_TYPE (decl)) == UNION_TYPE
|| TREE_CODE (TREE_TYPE (decl)) == QUAL_UNION_TYPE));
locus = IDENTIFIER_POINTER (DECL_NAME (decl));
}
else
{
require_constant_value = 0;
require_constant_elements = 0;
locus = "(anonymous)";
}
constructor_stack = 0;
constructor_range_stack = 0;
missing_braces_mentioned = 0;
spelling_base = 0;
spelling_size = 0;
RESTORE_SPELLING_DEPTH (0);
if (locus)
push_string (locus);
}
void
finish_init (void)
{
struct initializer_stack *p = initializer_stack;
/* Free the whole constructor stack of this initializer. */
while (constructor_stack)
{
struct constructor_stack *q = constructor_stack;
constructor_stack = q->next;
free (q);
}
gcc_assert (!constructor_range_stack);
/* Pop back to the data of the outer initializer (if any). */
free (spelling_base);
constructor_decl = p->decl;
require_constant_value = p->require_constant_value;
require_constant_elements = p->require_constant_elements;
constructor_stack = p->constructor_stack;
constructor_range_stack = p->constructor_range_stack;
constructor_elements = p->elements;
spelling = p->spelling;
spelling_base = p->spelling_base;
spelling_size = p->spelling_size;
constructor_top_level = p->top_level;
initializer_stack = p->next;
free (p);
}
/* Call here when we see the initializer is surrounded by braces.
This is instead of a call to push_init_level;
it is matched by a call to pop_init_level.
TYPE is the type to initialize, for a constructor expression.
For an initializer for a decl, TYPE is zero. */
void
really_start_incremental_init (tree type)
{
struct constructor_stack *p = XNEW (struct constructor_stack);
if (type == 0)
type = TREE_TYPE (constructor_decl);
if (targetm.vector_opaque_p (type))
error ("opaque vector types cannot be initialized");
p->type = constructor_type;
p->fields = constructor_fields;
p->index = constructor_index;
p->max_index = constructor_max_index;
p->unfilled_index = constructor_unfilled_index;
p->unfilled_fields = constructor_unfilled_fields;
p->bit_index = constructor_bit_index;
p->elements = constructor_elements;
p->constant = constructor_constant;
p->simple = constructor_simple;
p->erroneous = constructor_erroneous;
p->pending_elts = constructor_pending_elts;
p->depth = constructor_depth;
p->replacement_value.value = 0;
p->replacement_value.original_code = ERROR_MARK;
p->implicit = 0;
p->range_stack = 0;
p->outer = 0;
p->incremental = constructor_incremental;
p->designated = constructor_designated;
p->next = 0;
constructor_stack = p;
constructor_constant = 1;
constructor_simple = 1;
constructor_depth = SPELLING_DEPTH ();
constructor_elements = 0;
constructor_pending_elts = 0;
constructor_type = type;
constructor_incremental = 1;
constructor_designated = 0;
designator_depth = 0;
designator_erroneous = 0;
if (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
{
constructor_fields = TYPE_FIELDS (constructor_type);
/* Skip any nameless bit fields at the beginning. */
while (constructor_fields != 0 && DECL_C_BIT_FIELD (constructor_fields)
&& DECL_NAME (constructor_fields) == 0)
constructor_fields = TREE_CHAIN (constructor_fields);
constructor_unfilled_fields = constructor_fields;
constructor_bit_index = bitsize_zero_node;
}
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
if (TYPE_DOMAIN (constructor_type))
{
constructor_max_index
= TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type));
/* Detect non-empty initializations of zero-length arrays. */
if (constructor_max_index == NULL_TREE
&& TYPE_SIZE (constructor_type))
constructor_max_index = build_int_cst (NULL_TREE, -1);
/* constructor_max_index needs to be an INTEGER_CST. Attempts
to initialize VLAs will cause a proper error; avoid tree
checking errors as well by setting a safe value. */
if (constructor_max_index
&& TREE_CODE (constructor_max_index) != INTEGER_CST)
constructor_max_index = build_int_cst (NULL_TREE, -1);
constructor_index
= convert (bitsizetype,
TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type)));
}
else
{
constructor_index = bitsize_zero_node;
constructor_max_index = NULL_TREE;
}
constructor_unfilled_index = constructor_index;
}
else if (TREE_CODE (constructor_type) == VECTOR_TYPE)
{
/* Vectors are like simple fixed-size arrays. */
constructor_max_index =
build_int_cst (NULL_TREE, TYPE_VECTOR_SUBPARTS (constructor_type) - 1);
constructor_index = bitsize_zero_node;
constructor_unfilled_index = constructor_index;
}
else
{
/* Handle the case of int x = {5}; */
constructor_fields = constructor_type;
constructor_unfilled_fields = constructor_type;
}
}
/* Push down into a subobject, for initialization.
If this is for an explicit set of braces, IMPLICIT is 0.
If it is because the next element belongs at a lower level,
IMPLICIT is 1 (or 2 if the push is because of designator list). */
void
push_init_level (int implicit)
{
struct constructor_stack *p;
tree value = NULL_TREE;
/* If we've exhausted any levels that didn't have braces,
pop them now. If implicit == 1, this will have been done in
process_init_element; do not repeat it here because in the case
of excess initializers for an empty aggregate this leads to an
infinite cycle of popping a level and immediately recreating
it. */
if (implicit != 1)
{
while (constructor_stack->implicit)
{
if ((TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
&& constructor_fields == 0)
process_init_element (pop_init_level (1));
else if (TREE_CODE (constructor_type) == ARRAY_TYPE
&& constructor_max_index
&& tree_int_cst_lt (constructor_max_index,
constructor_index))
process_init_element (pop_init_level (1));
else
break;
}
}
/* Unless this is an explicit brace, we need to preserve previous
content if any. */
if (implicit)
{
if ((TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
&& constructor_fields)
value = find_init_member (constructor_fields);
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
value = find_init_member (constructor_index);
}
p = XNEW (struct constructor_stack);
p->type = constructor_type;
p->fields = constructor_fields;
p->index = constructor_index;
p->max_index = constructor_max_index;
p->unfilled_index = constructor_unfilled_index;
p->unfilled_fields = constructor_unfilled_fields;
p->bit_index = constructor_bit_index;
p->elements = constructor_elements;
p->constant = constructor_constant;
p->simple = constructor_simple;
p->erroneous = constructor_erroneous;
p->pending_elts = constructor_pending_elts;
p->depth = constructor_depth;
p->replacement_value.value = 0;
p->replacement_value.original_code = ERROR_MARK;
p->implicit = implicit;
p->outer = 0;
p->incremental = constructor_incremental;
p->designated = constructor_designated;
p->next = constructor_stack;
p->range_stack = 0;
constructor_stack = p;
constructor_constant = 1;
constructor_simple = 1;
constructor_depth = SPELLING_DEPTH ();
constructor_elements = 0;
constructor_incremental = 1;
constructor_designated = 0;
constructor_pending_elts = 0;
if (!implicit)
{
p->range_stack = constructor_range_stack;
constructor_range_stack = 0;
designator_depth = 0;
designator_erroneous = 0;
}
/* Don't die if an entire brace-pair level is superfluous
in the containing level. */
if (constructor_type == 0)
;
else if (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
{
/* Don't die if there are extra init elts at the end. */
if (constructor_fields == 0)
constructor_type = 0;
else
{
constructor_type = TREE_TYPE (constructor_fields);
push_member_name (constructor_fields);
constructor_depth++;
}
}
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
constructor_type = TREE_TYPE (constructor_type);
push_array_bounds (tree_low_cst (constructor_index, 1));
constructor_depth++;
}
if (constructor_type == 0)
{
error_init ("extra brace group at end of initializer");
constructor_fields = 0;
constructor_unfilled_fields = 0;
return;
}
if (value && TREE_CODE (value) == CONSTRUCTOR)
{
constructor_constant = TREE_CONSTANT (value);
constructor_simple = TREE_STATIC (value);
constructor_elements = CONSTRUCTOR_ELTS (value);
if (!VEC_empty (constructor_elt, constructor_elements)
&& (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == ARRAY_TYPE))
set_nonincremental_init ();
}
if (implicit == 1 && warn_missing_braces && !missing_braces_mentioned)
{
missing_braces_mentioned = 1;
warning_init ("missing braces around initializer");
}
if (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
{
constructor_fields = TYPE_FIELDS (constructor_type);
/* Skip any nameless bit fields at the beginning. */
while (constructor_fields != 0 && DECL_C_BIT_FIELD (constructor_fields)
&& DECL_NAME (constructor_fields) == 0)
constructor_fields = TREE_CHAIN (constructor_fields);
constructor_unfilled_fields = constructor_fields;
constructor_bit_index = bitsize_zero_node;
}
else if (TREE_CODE (constructor_type) == VECTOR_TYPE)
{
/* Vectors are like simple fixed-size arrays. */
constructor_max_index =
build_int_cst (NULL_TREE, TYPE_VECTOR_SUBPARTS (constructor_type) - 1);
constructor_index = convert (bitsizetype, integer_zero_node);
constructor_unfilled_index = constructor_index;
}
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
if (TYPE_DOMAIN (constructor_type))
{
constructor_max_index
= TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type));
/* Detect non-empty initializations of zero-length arrays. */
if (constructor_max_index == NULL_TREE
&& TYPE_SIZE (constructor_type))
constructor_max_index = build_int_cst (NULL_TREE, -1);
/* constructor_max_index needs to be an INTEGER_CST. Attempts
to initialize VLAs will cause a proper error; avoid tree
checking errors as well by setting a safe value. */
if (constructor_max_index
&& TREE_CODE (constructor_max_index) != INTEGER_CST)
constructor_max_index = build_int_cst (NULL_TREE, -1);
constructor_index
= convert (bitsizetype,
TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type)));
}
else
constructor_index = bitsize_zero_node;
constructor_unfilled_index = constructor_index;
if (value && TREE_CODE (value) == STRING_CST)
{
/* We need to split the char/wchar array into individual
characters, so that we don't have to special case it
everywhere. */
set_nonincremental_init_from_string (value);
}
}
else
{
if (constructor_type != error_mark_node)
warning_init ("braces around scalar initializer");
constructor_fields = constructor_type;
constructor_unfilled_fields = constructor_type;
}
}
/* At the end of an implicit or explicit brace level,
finish up that level of constructor. If a single expression
with redundant braces initialized that level, return the
c_expr structure for that expression. Otherwise, the original_code
element is set to ERROR_MARK.
If we were outputting the elements as they are read, return 0 as the value
from inner levels (process_init_element ignores that),
but return error_mark_node as the value from the outermost level
(that's what we want to put in DECL_INITIAL).
Otherwise, return a CONSTRUCTOR expression as the value. */
struct c_expr
pop_init_level (int implicit)
{
struct constructor_stack *p;
struct c_expr ret;
ret.value = 0;
ret.original_code = ERROR_MARK;
if (implicit == 0)
{
/* When we come to an explicit close brace,
pop any inner levels that didn't have explicit braces. */
while (constructor_stack->implicit)
process_init_element (pop_init_level (1));
gcc_assert (!constructor_range_stack);
}
/* Now output all pending elements. */
constructor_incremental = 1;
output_pending_init_elements (1);
p = constructor_stack;
/* Error for initializing a flexible array member, or a zero-length
array member in an inappropriate context. */
if (constructor_type && constructor_fields
&& TREE_CODE (constructor_type) == ARRAY_TYPE
&& TYPE_DOMAIN (constructor_type)
&& !TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type)))
{
/* Silently discard empty initializations. The parser will
already have pedwarned for empty brackets. */
if (integer_zerop (constructor_unfilled_index))
constructor_type = NULL_TREE;
else
{
gcc_assert (!TYPE_SIZE (constructor_type));
if (constructor_depth > 2)
error_init ("initialization of flexible array member in a nested context");
else if (pedantic)
pedwarn_init ("initialization of a flexible array member");
/* We have already issued an error message for the existence
of a flexible array member not at the end of the structure.
Discard the initializer so that we do not die later. */
if (TREE_CHAIN (constructor_fields) != NULL_TREE)
constructor_type = NULL_TREE;
}
}
/* Warn when some struct elements are implicitly initialized to zero. */
if (warn_missing_field_initializers
&& constructor_type
&& TREE_CODE (constructor_type) == RECORD_TYPE
&& constructor_unfilled_fields)
{
/* Do not warn for flexible array members or zero-length arrays. */
while (constructor_unfilled_fields
&& (!DECL_SIZE (constructor_unfilled_fields)
|| integer_zerop (DECL_SIZE (constructor_unfilled_fields))))
constructor_unfilled_fields = TREE_CHAIN (constructor_unfilled_fields);
/* Do not warn if this level of the initializer uses member
designators; it is likely to be deliberate. */
if (constructor_unfilled_fields && !constructor_designated)
{
push_member_name (constructor_unfilled_fields);
warning_init ("missing initializer");
RESTORE_SPELLING_DEPTH (constructor_depth);
}
}
/* Pad out the end of the structure. */
if (p->replacement_value.value)
/* If this closes a superfluous brace pair,
just pass out the element between them. */
ret = p->replacement_value;
else if (constructor_type == 0)
;
else if (TREE_CODE (constructor_type) != RECORD_TYPE
&& TREE_CODE (constructor_type) != UNION_TYPE
&& TREE_CODE (constructor_type) != ARRAY_TYPE
&& TREE_CODE (constructor_type) != VECTOR_TYPE)
{
/* A nonincremental scalar initializer--just return
the element, after verifying there is just one. */
if (VEC_empty (constructor_elt,constructor_elements))
{
if (!constructor_erroneous)
error_init ("empty scalar initializer");
ret.value = error_mark_node;
}
else if (VEC_length (constructor_elt,constructor_elements) != 1)
{
error_init ("extra elements in scalar initializer");
ret.value = VEC_index (constructor_elt,constructor_elements,0)->value;
}
else
ret.value = VEC_index (constructor_elt,constructor_elements,0)->value;
}
else
{
if (constructor_erroneous)
ret.value = error_mark_node;
else
{
ret.value = build_constructor (constructor_type,
constructor_elements);
if (constructor_constant)
TREE_CONSTANT (ret.value) = TREE_INVARIANT (ret.value) = 1;
if (constructor_constant && constructor_simple)
TREE_STATIC (ret.value) = 1;
}
}
constructor_type = p->type;
constructor_fields = p->fields;
constructor_index = p->index;
constructor_max_index = p->max_index;
constructor_unfilled_index = p->unfilled_index;
constructor_unfilled_fields = p->unfilled_fields;
constructor_bit_index = p->bit_index;
constructor_elements = p->elements;
constructor_constant = p->constant;
constructor_simple = p->simple;
constructor_erroneous = p->erroneous;
constructor_incremental = p->incremental;
constructor_designated = p->designated;
constructor_pending_elts = p->pending_elts;
constructor_depth = p->depth;
if (!p->implicit)
constructor_range_stack = p->range_stack;
RESTORE_SPELLING_DEPTH (constructor_depth);
constructor_stack = p->next;
free (p);
if (ret.value == 0 && constructor_stack == 0)
ret.value = error_mark_node;
return ret;
}
/* Common handling for both array range and field name designators.
ARRAY argument is nonzero for array ranges. Returns zero for success. */
static int
set_designator (int array)
{
tree subtype;
enum tree_code subcode;
/* Don't die if an entire brace-pair level is superfluous
in the containing level. */
if (constructor_type == 0)
return 1;
/* If there were errors in this designator list already, bail out
silently. */
if (designator_erroneous)
return 1;
if (!designator_depth)
{
gcc_assert (!constructor_range_stack);
/* Designator list starts at the level of closest explicit
braces. */
while (constructor_stack->implicit)
process_init_element (pop_init_level (1));
constructor_designated = 1;
return 0;
}
switch (TREE_CODE (constructor_type))
{
case RECORD_TYPE:
case UNION_TYPE:
subtype = TREE_TYPE (constructor_fields);
if (subtype != error_mark_node)
subtype = TYPE_MAIN_VARIANT (subtype);
break;
case ARRAY_TYPE:
subtype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type));
break;
default:
gcc_unreachable ();
}
subcode = TREE_CODE (subtype);
if (array && subcode != ARRAY_TYPE)
{
error_init ("array index in non-array initializer");
return 1;
}
else if (!array && subcode != RECORD_TYPE && subcode != UNION_TYPE)
{
error_init ("field name not in record or union initializer");
return 1;
}
constructor_designated = 1;
push_init_level (2);
return 0;
}
/* If there are range designators in designator list, push a new designator
to constructor_range_stack. RANGE_END is end of such stack range or
NULL_TREE if there is no range designator at this level. */
static void
push_range_stack (tree range_end)
{
struct constructor_range_stack *p;
p = GGC_NEW (struct constructor_range_stack);
p->prev = constructor_range_stack;
p->next = 0;
p->fields = constructor_fields;
p->range_start = constructor_index;
p->index = constructor_index;
p->stack = constructor_stack;
p->range_end = range_end;
if (constructor_range_stack)
constructor_range_stack->next = p;
constructor_range_stack = p;
}
/* Within an array initializer, specify the next index to be initialized.
FIRST is that index. If LAST is nonzero, then initialize a range
of indices, running from FIRST through LAST. */
void
set_init_index (tree first, tree last)
{
if (set_designator (1))
return;
designator_erroneous = 1;
if (!INTEGRAL_TYPE_P (TREE_TYPE (first))
|| (last && !INTEGRAL_TYPE_P (TREE_TYPE (last))))
{
error_init ("array index in initializer not of integer type");
return;
}
if (TREE_CODE (first) != INTEGER_CST)
error_init ("nonconstant array index in initializer");
else if (last != 0 && TREE_CODE (last) != INTEGER_CST)
error_init ("nonconstant array index in initializer");
else if (TREE_CODE (constructor_type) != ARRAY_TYPE)
error_init ("array index in non-array initializer");
else if (tree_int_cst_sgn (first) == -1)
error_init ("array index in initializer exceeds array bounds");
else if (constructor_max_index
&& tree_int_cst_lt (constructor_max_index, first))
error_init ("array index in initializer exceeds array bounds");
else
{
constructor_index = convert (bitsizetype, first);
if (last)
{
if (tree_int_cst_equal (first, last))
last = 0;
else if (tree_int_cst_lt (last, first))
{
error_init ("empty index range in initializer");
last = 0;
}
else
{
last = convert (bitsizetype, last);
if (constructor_max_index != 0
&& tree_int_cst_lt (constructor_max_index, last))
{
error_init ("array index range in initializer exceeds array bounds");
last = 0;
}
}
}
designator_depth++;
designator_erroneous = 0;
if (constructor_range_stack || last)
push_range_stack (last);
}
}
/* Within a struct initializer, specify the next field to be initialized. */
void
set_init_label (tree fieldname)
{
tree tail;
if (set_designator (0))
return;
designator_erroneous = 1;
if (TREE_CODE (constructor_type) != RECORD_TYPE
&& TREE_CODE (constructor_type) != UNION_TYPE)
{
error_init ("field name not in record or union initializer");
return;
}
for (tail = TYPE_FIELDS (constructor_type); tail;
tail = TREE_CHAIN (tail))
{
if (DECL_NAME (tail) == fieldname)
break;
}
if (tail == 0)
error ("unknown field %qE specified in initializer", fieldname);
else
{
constructor_fields = tail;
designator_depth++;
designator_erroneous = 0;
if (constructor_range_stack)
push_range_stack (NULL_TREE);
}
}
/* Add a new initializer to the tree of pending initializers. PURPOSE
identifies the initializer, either array index or field in a structure.
VALUE is the value of that index or field. */
static void
add_pending_init (tree purpose, tree value)
{
struct init_node *p, **q, *r;
q = &constructor_pending_elts;
p = 0;
if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
while (*q != 0)
{
p = *q;
if (tree_int_cst_lt (purpose, p->purpose))
q = &p->left;
else if (tree_int_cst_lt (p->purpose, purpose))
q = &p->right;
else
{
if (TREE_SIDE_EFFECTS (p->value))
warning_init ("initialized field with side-effects overwritten");
else if (warn_override_init)
warning_init ("initialized field overwritten");
p->value = value;
return;
}
}
}
else
{
tree bitpos;
bitpos = bit_position (purpose);
while (*q != NULL)
{
p = *q;
if (tree_int_cst_lt (bitpos, bit_position (p->purpose)))
q = &p->left;
else if (p->purpose != purpose)
q = &p->right;
else
{
if (TREE_SIDE_EFFECTS (p->value))
warning_init ("initialized field with side-effects overwritten");
else if (warn_override_init)
warning_init ("initialized field overwritten");
p->value = value;
return;
}
}
}
r = GGC_NEW (struct init_node);
r->purpose = purpose;
r->value = value;
*q = r;
r->parent = p;
r->left = 0;
r->right = 0;
r->balance = 0;
while (p)
{
struct init_node *s;
if (r == p->left)
{
if (p->balance == 0)
p->balance = -1;
else if (p->balance < 0)
{
if (r->balance < 0)
{
/* L rotation. */
p->left = r->right;
if (p->left)
p->left->parent = p;
r->right = p;
p->balance = 0;
r->balance = 0;
s = p->parent;
p->parent = r;
r->parent = s;
if (s)
{
if (s->left == p)
s->left = r;
else
s->right = r;
}
else
constructor_pending_elts = r;
}
else
{
/* LR rotation. */
struct init_node *t = r->right;
r->right = t->left;
if (r->right)
r->right->parent = r;
t->left = r;
p->left = t->right;
if (p->left)
p->left->parent = p;
t->right = p;
p->balance = t->balance < 0;
r->balance = -(t->balance > 0);
t->balance = 0;
s = p->parent;
p->parent = t;
r->parent = t;
t->parent = s;
if (s)
{
if (s->left == p)
s->left = t;
else
s->right = t;
}
else
constructor_pending_elts = t;
}
break;
}
else
{
/* p->balance == +1; growth of left side balances the node. */
p->balance = 0;
break;
}
}
else /* r == p->right */
{
if (p->balance == 0)
/* Growth propagation from right side. */
p->balance++;
else if (p->balance > 0)
{
if (r->balance > 0)
{
/* R rotation. */
p->right = r->left;
if (p->right)
p->right->parent = p;
r->left = p;
p->balance = 0;
r->balance = 0;
s = p->parent;
p->parent = r;
r->parent = s;
if (s)
{
if (s->left == p)
s->left = r;
else
s->right = r;
}
else
constructor_pending_elts = r;
}
else /* r->balance == -1 */
{
/* RL rotation */
struct init_node *t = r->left;
r->left = t->right;
if (r->left)
r->left->parent = r;
t->right = r;
p->right = t->left;
if (p->right)
p->right->parent = p;
t->left = p;
r->balance = (t->balance < 0);
p->balance = -(t->balance > 0);
t->balance = 0;
s = p->parent;
p->parent = t;
r->parent = t;
t->parent = s;
if (s)
{
if (s->left == p)
s->left = t;
else
s->right = t;
}
else
constructor_pending_elts = t;
}
break;
}
else
{
/* p->balance == -1; growth of right side balances the node. */
p->balance = 0;
break;
}
}
r = p;
p = p->parent;
}
}
/* Build AVL tree from a sorted chain. */
static void
set_nonincremental_init (void)
{
unsigned HOST_WIDE_INT ix;
tree index, value;
if (TREE_CODE (constructor_type) != RECORD_TYPE
&& TREE_CODE (constructor_type) != ARRAY_TYPE)
return;
FOR_EACH_CONSTRUCTOR_ELT (constructor_elements, ix, index, value)
add_pending_init (index, value);
constructor_elements = 0;
if (TREE_CODE (constructor_type) == RECORD_TYPE)
{
constructor_unfilled_fields = TYPE_FIELDS (constructor_type);
/* Skip any nameless bit fields at the beginning. */
while (constructor_unfilled_fields != 0
&& DECL_C_BIT_FIELD (constructor_unfilled_fields)
&& DECL_NAME (constructor_unfilled_fields) == 0)
constructor_unfilled_fields = TREE_CHAIN (constructor_unfilled_fields);
}
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
if (TYPE_DOMAIN (constructor_type))
constructor_unfilled_index
= convert (bitsizetype,
TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type)));
else
constructor_unfilled_index = bitsize_zero_node;
}
constructor_incremental = 0;
}
/* Build AVL tree from a string constant. */
static void
set_nonincremental_init_from_string (tree str)
{
tree value, purpose, type;
HOST_WIDE_INT val[2];
const char *p, *end;
int byte, wchar_bytes, charwidth, bitpos;
gcc_assert (TREE_CODE (constructor_type) == ARRAY_TYPE);
if (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (str)))
== TYPE_PRECISION (char_type_node))
wchar_bytes = 1;
else
{
gcc_assert (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (str)))
== TYPE_PRECISION (wchar_type_node));
wchar_bytes = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
}
charwidth = TYPE_PRECISION (char_type_node);
type = TREE_TYPE (constructor_type);
p = TREE_STRING_POINTER (str);
end = p + TREE_STRING_LENGTH (str);
for (purpose = bitsize_zero_node;
p < end && !tree_int_cst_lt (constructor_max_index, purpose);
purpose = size_binop (PLUS_EXPR, purpose, bitsize_one_node))
{
if (wchar_bytes == 1)
{
val[1] = (unsigned char) *p++;
val[0] = 0;
}
else
{
val[0] = 0;
val[1] = 0;
for (byte = 0; byte < wchar_bytes; byte++)
{
if (BYTES_BIG_ENDIAN)
bitpos = (wchar_bytes - byte - 1) * charwidth;
else
bitpos = byte * charwidth;
val[bitpos < HOST_BITS_PER_WIDE_INT]
|= ((unsigned HOST_WIDE_INT) ((unsigned char) *p++))
<< (bitpos % HOST_BITS_PER_WIDE_INT);
}
}
if (!TYPE_UNSIGNED (type))
{
bitpos = ((wchar_bytes - 1) * charwidth) + HOST_BITS_PER_CHAR;
if (bitpos < HOST_BITS_PER_WIDE_INT)
{
if (val[1] & (((HOST_WIDE_INT) 1) << (bitpos - 1)))
{
val[1] |= ((HOST_WIDE_INT) -1) << bitpos;
val[0] = -1;
}
}
else if (bitpos == HOST_BITS_PER_WIDE_INT)
{
if (val[1] < 0)
val[0] = -1;
}
else if (val[0] & (((HOST_WIDE_INT) 1)
<< (bitpos - 1 - HOST_BITS_PER_WIDE_INT)))
val[0] |= ((HOST_WIDE_INT) -1)
<< (bitpos - HOST_BITS_PER_WIDE_INT);
}
value = build_int_cst_wide (type, val[1], val[0]);
add_pending_init (purpose, value);
}
constructor_incremental = 0;
}
/* Return value of FIELD in pending initializer or zero if the field was
not initialized yet. */
static tree
find_init_member (tree field)
{
struct init_node *p;
if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
if (constructor_incremental
&& tree_int_cst_lt (field, constructor_unfilled_index))
set_nonincremental_init ();
p = constructor_pending_elts;
while (p)
{
if (tree_int_cst_lt (field, p->purpose))
p = p->left;
else if (tree_int_cst_lt (p->purpose, field))
p = p->right;
else
return p->value;
}
}
else if (TREE_CODE (constructor_type) == RECORD_TYPE)
{
tree bitpos = bit_position (field);
if (constructor_incremental
&& (!constructor_unfilled_fields
|| tree_int_cst_lt (bitpos,
bit_position (constructor_unfilled_fields))))
set_nonincremental_init ();
p = constructor_pending_elts;
while (p)
{
if (field == p->purpose)
return p->value;
else if (tree_int_cst_lt (bitpos, bit_position (p->purpose)))
p = p->left;
else
p = p->right;
}
}
else if (TREE_CODE (constructor_type) == UNION_TYPE)
{
if (!VEC_empty (constructor_elt, constructor_elements)
&& (VEC_last (constructor_elt, constructor_elements)->index
== field))
return VEC_last (constructor_elt, constructor_elements)->value;
}
return 0;
}
/* "Output" the next constructor element.
At top level, really output it to assembler code now.
Otherwise, collect it in a list from which we will make a CONSTRUCTOR.
TYPE is the data type that the containing data type wants here.
FIELD is the field (a FIELD_DECL) or the index that this element fills.
If VALUE is a string constant, STRICT_STRING is true if it is
unparenthesized or we should not warn here for it being parenthesized.
For other types of VALUE, STRICT_STRING is not used.
PENDING if non-nil means output pending elements that belong
right after this element. (PENDING is normally 1;
it is 0 while outputting pending elements, to avoid recursion.) */
static void
output_init_element (tree value, bool strict_string, tree type, tree field,
int pending)
{
constructor_elt *celt;
if (type == error_mark_node || value == error_mark_node)
{
constructor_erroneous = 1;
return;
}
if (TREE_CODE (TREE_TYPE (value)) == ARRAY_TYPE
&& (TREE_CODE (value) == STRING_CST
|| TREE_CODE (value) == COMPOUND_LITERAL_EXPR)
&& !(TREE_CODE (value) == STRING_CST
&& TREE_CODE (type) == ARRAY_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (type)))
&& !comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (value)),
TYPE_MAIN_VARIANT (type)))
value = array_to_pointer_conversion (value);
if (TREE_CODE (value) == COMPOUND_LITERAL_EXPR
&& require_constant_value && !flag_isoc99 && pending)
{
/* As an extension, allow initializing objects with static storage
duration with compound literals (which are then treated just as
the brace enclosed list they contain). */
tree decl = COMPOUND_LITERAL_EXPR_DECL (value);
value = DECL_INITIAL (decl);
}
if (value == error_mark_node)
constructor_erroneous = 1;
else if (!TREE_CONSTANT (value))
constructor_constant = 0;
else if (!initializer_constant_valid_p (value, TREE_TYPE (value))
|| ((TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
&& DECL_C_BIT_FIELD (field)
&& TREE_CODE (value) != INTEGER_CST))
constructor_simple = 0;
if (!initializer_constant_valid_p (value, TREE_TYPE (value)))
{
if (require_constant_value)
{
error_init ("initializer element is not constant");
value = error_mark_node;
}
else if (require_constant_elements)
pedwarn ("initializer element is not computable at load time");
}
/* If this field is empty (and not at the end of structure),
don't do anything other than checking the initializer. */
if (field
&& (TREE_TYPE (field) == error_mark_node
|| (COMPLETE_TYPE_P (TREE_TYPE (field))
&& integer_zerop (TYPE_SIZE (TREE_TYPE (field)))
&& (TREE_CODE (constructor_type) == ARRAY_TYPE
|| TREE_CHAIN (field)))))
return;
value = digest_init (type, value, strict_string, require_constant_value);
if (value == error_mark_node)
{
constructor_erroneous = 1;
return;
}
/* If this element doesn't come next in sequence,
put it on constructor_pending_elts. */
if (TREE_CODE (constructor_type) == ARRAY_TYPE
&& (!constructor_incremental
|| !tree_int_cst_equal (field, constructor_unfilled_index)))
{
if (constructor_incremental
&& tree_int_cst_lt (field, constructor_unfilled_index))
set_nonincremental_init ();
add_pending_init (field, value);
return;
}
else if (TREE_CODE (constructor_type) == RECORD_TYPE
&& (!constructor_incremental
|| field != constructor_unfilled_fields))
{
/* We do this for records but not for unions. In a union,
no matter which field is specified, it can be initialized
right away since it starts at the beginning of the union. */
if (constructor_incremental)
{
if (!constructor_unfilled_fields)
set_nonincremental_init ();
else
{
tree bitpos, unfillpos;
bitpos = bit_position (field);
unfillpos = bit_position (constructor_unfilled_fields);
if (tree_int_cst_lt (bitpos, unfillpos))
set_nonincremental_init ();
}
}
add_pending_init (field, value);
return;
}
else if (TREE_CODE (constructor_type) == UNION_TYPE
&& !VEC_empty (constructor_elt, constructor_elements))
{
if (TREE_SIDE_EFFECTS (VEC_last (constructor_elt,
constructor_elements)->value))
warning_init ("initialized field with side-effects overwritten");
else if (warn_override_init)
warning_init ("initialized field overwritten");
/* We can have just one union field set. */
constructor_elements = 0;
}
/* Otherwise, output this element either to
constructor_elements or to the assembler file. */
celt = VEC_safe_push (constructor_elt, gc, constructor_elements, NULL);
celt->index = field;
celt->value = value;
/* Advance the variable that indicates sequential elements output. */
if (TREE_CODE (constructor_type) == ARRAY_TYPE)
constructor_unfilled_index
= size_binop (PLUS_EXPR, constructor_unfilled_index,
bitsize_one_node);
else if (TREE_CODE (constructor_type) == RECORD_TYPE)
{
constructor_unfilled_fields
= TREE_CHAIN (constructor_unfilled_fields);
/* Skip any nameless bit fields. */
while (constructor_unfilled_fields != 0
&& DECL_C_BIT_FIELD (constructor_unfilled_fields)
&& DECL_NAME (constructor_unfilled_fields) == 0)
constructor_unfilled_fields =
TREE_CHAIN (constructor_unfilled_fields);
}
else if (TREE_CODE (constructor_type) == UNION_TYPE)
constructor_unfilled_fields = 0;
/* Now output any pending elements which have become next. */
if (pending)
output_pending_init_elements (0);
}
/* Output any pending elements which have become next.
As we output elements, constructor_unfilled_{fields,index}
advances, which may cause other elements to become next;
if so, they too are output.
If ALL is 0, we return when there are
no more pending elements to output now.
If ALL is 1, we output space as necessary so that
we can output all the pending elements. */
static void
output_pending_init_elements (int all)
{
struct init_node *elt = constructor_pending_elts;
tree next;
retry:
/* Look through the whole pending tree.
If we find an element that should be output now,
output it. Otherwise, set NEXT to the element
that comes first among those still pending. */
next = 0;
while (elt)
{
if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
if (tree_int_cst_equal (elt->purpose,
constructor_unfilled_index))
output_init_element (elt->value, true,
TREE_TYPE (constructor_type),
constructor_unfilled_index, 0);
else if (tree_int_cst_lt (constructor_unfilled_index,
elt->purpose))
{
/* Advance to the next smaller node. */
if (elt->left)
elt = elt->left;
else
{
/* We have reached the smallest node bigger than the
current unfilled index. Fill the space first. */
next = elt->purpose;
break;
}
}
else
{
/* Advance to the next bigger node. */
if (elt->right)
elt = elt->right;
else
{
/* We have reached the biggest node in a subtree. Find
the parent of it, which is the next bigger node. */
while (elt->parent && elt->parent->right == elt)
elt = elt->parent;
elt = elt->parent;
if (elt && tree_int_cst_lt (constructor_unfilled_index,
elt->purpose))
{
next = elt->purpose;
break;
}
}
}
}
else if (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
{
tree ctor_unfilled_bitpos, elt_bitpos;
/* If the current record is complete we are done. */
if (constructor_unfilled_fields == 0)
break;
ctor_unfilled_bitpos = bit_position (constructor_unfilled_fields);
elt_bitpos = bit_position (elt->purpose);
/* We can't compare fields here because there might be empty
fields in between. */
if (tree_int_cst_equal (elt_bitpos, ctor_unfilled_bitpos))
{
constructor_unfilled_fields = elt->purpose;
output_init_element (elt->value, true, TREE_TYPE (elt->purpose),
elt->purpose, 0);
}
else if (tree_int_cst_lt (ctor_unfilled_bitpos, elt_bitpos))
{
/* Advance to the next smaller node. */
if (elt->left)
elt = elt->left;
else
{
/* We have reached the smallest node bigger than the
current unfilled field. Fill the space first. */
next = elt->purpose;
break;
}
}
else
{
/* Advance to the next bigger node. */
if (elt->right)
elt = elt->right;
else
{
/* We have reached the biggest node in a subtree. Find
the parent of it, which is the next bigger node. */
while (elt->parent && elt->parent->right == elt)
elt = elt->parent;
elt = elt->parent;
if (elt
&& (tree_int_cst_lt (ctor_unfilled_bitpos,
bit_position (elt->purpose))))
{
next = elt->purpose;
break;
}
}
}
}
}
/* Ordinarily return, but not if we want to output all
and there are elements left. */
if (!(all && next != 0))
return;
/* If it's not incremental, just skip over the gap, so that after
jumping to retry we will output the next successive element. */
if (TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
constructor_unfilled_fields = next;
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
constructor_unfilled_index = next;
/* ELT now points to the node in the pending tree with the next
initializer to output. */
goto retry;
}
/* Add one non-braced element to the current constructor level.
This adjusts the current position within the constructor's type.
This may also start or terminate implicit levels
to handle a partly-braced initializer.
Once this has found the correct level for the new element,
it calls output_init_element. */
void
process_init_element (struct c_expr value)
{
tree orig_value = value.value;
int string_flag = orig_value != 0 && TREE_CODE (orig_value) == STRING_CST;
bool strict_string = value.original_code == STRING_CST;
designator_depth = 0;
designator_erroneous = 0;
/* Handle superfluous braces around string cst as in
char x[] = {"foo"}; */
if (string_flag
&& constructor_type
&& TREE_CODE (constructor_type) == ARRAY_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (constructor_type))
&& integer_zerop (constructor_unfilled_index))
{
if (constructor_stack->replacement_value.value)
error_init ("excess elements in char array initializer");
constructor_stack->replacement_value = value;
return;
}
if (constructor_stack->replacement_value.value != 0)
{
error_init ("excess elements in struct initializer");
return;
}
/* Ignore elements of a brace group if it is entirely superfluous
and has already been diagnosed. */
if (constructor_type == 0)
return;
/* If we've exhausted any levels that didn't have braces,
pop them now. */
while (constructor_stack->implicit)
{
if ((TREE_CODE (constructor_type) == RECORD_TYPE
|| TREE_CODE (constructor_type) == UNION_TYPE)
&& constructor_fields == 0)
process_init_element (pop_init_level (1));
else if (TREE_CODE (constructor_type) == ARRAY_TYPE
&& (constructor_max_index == 0
|| tree_int_cst_lt (constructor_max_index,
constructor_index)))
process_init_element (pop_init_level (1));
else
break;
}
/* In the case of [LO ... HI] = VALUE, only evaluate VALUE once. */
if (constructor_range_stack)
{
/* If value is a compound literal and we'll be just using its
content, don't put it into a SAVE_EXPR. */
if (TREE_CODE (value.value) != COMPOUND_LITERAL_EXPR
|| !require_constant_value
|| flag_isoc99)
value.value = save_expr (value.value);
}
while (1)
{
if (TREE_CODE (constructor_type) == RECORD_TYPE)
{
tree fieldtype;
enum tree_code fieldcode;
if (constructor_fields == 0)
{
pedwarn_init ("excess elements in struct initializer");
break;
}
fieldtype = TREE_TYPE (constructor_fields);
if (fieldtype != error_mark_node)
fieldtype = TYPE_MAIN_VARIANT (fieldtype);
fieldcode = TREE_CODE (fieldtype);
/* Error for non-static initialization of a flexible array member. */
if (fieldcode == ARRAY_TYPE
&& !require_constant_value
&& TYPE_SIZE (fieldtype) == NULL_TREE
&& TREE_CHAIN (constructor_fields) == NULL_TREE)
{
error_init ("non-static initialization of a flexible array member");
break;
}
/* Accept a string constant to initialize a subarray. */
if (value.value != 0
&& fieldcode == ARRAY_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (fieldtype))
&& string_flag)
value.value = orig_value;
/* Otherwise, if we have come to a subaggregate,
and we don't have an element of its type, push into it. */
else if (value.value != 0
&& value.value != error_mark_node
&& TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != fieldtype
&& (fieldcode == RECORD_TYPE || fieldcode == ARRAY_TYPE
|| fieldcode == UNION_TYPE))
{
push_init_level (1);
continue;
}
if (value.value)
{
push_member_name (constructor_fields);
output_init_element (value.value, strict_string,
fieldtype, constructor_fields, 1);
RESTORE_SPELLING_DEPTH (constructor_depth);
}
else
/* Do the bookkeeping for an element that was
directly output as a constructor. */
{
/* For a record, keep track of end position of last field. */
if (DECL_SIZE (constructor_fields))
constructor_bit_index
= size_binop (PLUS_EXPR,
bit_position (constructor_fields),
DECL_SIZE (constructor_fields));
/* If the current field was the first one not yet written out,
it isn't now, so update. */
if (constructor_unfilled_fields == constructor_fields)
{
constructor_unfilled_fields = TREE_CHAIN (constructor_fields);
/* Skip any nameless bit fields. */
while (constructor_unfilled_fields != 0
&& DECL_C_BIT_FIELD (constructor_unfilled_fields)
&& DECL_NAME (constructor_unfilled_fields) == 0)
constructor_unfilled_fields =
TREE_CHAIN (constructor_unfilled_fields);
}
}
constructor_fields = TREE_CHAIN (constructor_fields);
/* Skip any nameless bit fields at the beginning. */
while (constructor_fields != 0
&& DECL_C_BIT_FIELD (constructor_fields)
&& DECL_NAME (constructor_fields) == 0)
constructor_fields = TREE_CHAIN (constructor_fields);
}
else if (TREE_CODE (constructor_type) == UNION_TYPE)
{
tree fieldtype;
enum tree_code fieldcode;
if (constructor_fields == 0)
{
pedwarn_init ("excess elements in union initializer");
break;
}
fieldtype = TREE_TYPE (constructor_fields);
if (fieldtype != error_mark_node)
fieldtype = TYPE_MAIN_VARIANT (fieldtype);
fieldcode = TREE_CODE (fieldtype);
/* Warn that traditional C rejects initialization of unions.
We skip the warning if the value is zero. This is done
under the assumption that the zero initializer in user
code appears conditioned on e.g. __STDC__ to avoid
"missing initializer" warnings and relies on default
initialization to zero in the traditional C case.
We also skip the warning if the initializer is designated,
again on the assumption that this must be conditional on
__STDC__ anyway (and we've already complained about the
member-designator already). */
if (!in_system_header && !constructor_designated
&& !(value.value && (integer_zerop (value.value)
|| real_zerop (value.value))))
warning (OPT_Wtraditional, "traditional C rejects initialization "
"of unions");
/* Accept a string constant to initialize a subarray. */
if (value.value != 0
&& fieldcode == ARRAY_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (fieldtype))
&& string_flag)
value.value = orig_value;
/* Otherwise, if we have come to a subaggregate,
and we don't have an element of its type, push into it. */
else if (value.value != 0
&& value.value != error_mark_node
&& TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != fieldtype
&& (fieldcode == RECORD_TYPE || fieldcode == ARRAY_TYPE
|| fieldcode == UNION_TYPE))
{
push_init_level (1);
continue;
}
if (value.value)
{
push_member_name (constructor_fields);
output_init_element (value.value, strict_string,
fieldtype, constructor_fields, 1);
RESTORE_SPELLING_DEPTH (constructor_depth);
}
else
/* Do the bookkeeping for an element that was
directly output as a constructor. */
{
constructor_bit_index = DECL_SIZE (constructor_fields);
constructor_unfilled_fields = TREE_CHAIN (constructor_fields);
}
constructor_fields = 0;
}
else if (TREE_CODE (constructor_type) == ARRAY_TYPE)
{
tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type));
enum tree_code eltcode = TREE_CODE (elttype);
/* Accept a string constant to initialize a subarray. */
if (value.value != 0
&& eltcode == ARRAY_TYPE
&& INTEGRAL_TYPE_P (TREE_TYPE (elttype))
&& string_flag)
value.value = orig_value;
/* Otherwise, if we have come to a subaggregate,
and we don't have an element of its type, push into it. */
else if (value.value != 0
&& value.value != error_mark_node
&& TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != elttype
&& (eltcode == RECORD_TYPE || eltcode == ARRAY_TYPE
|| eltcode == UNION_TYPE))
{
push_init_level (1);
continue;
}
if (constructor_max_index != 0
&& (tree_int_cst_lt (constructor_max_index, constructor_index)
|| integer_all_onesp (constructor_max_index)))
{
pedwarn_init ("excess elements in array initializer");
break;
}
/* Now output the actual element. */
if (value.value)
{
push_array_bounds (tree_low_cst (constructor_index, 1));
output_init_element (value.value, strict_string,
elttype, constructor_index, 1);
RESTORE_SPELLING_DEPTH (constructor_depth);
}
constructor_index
= size_binop (PLUS_EXPR, constructor_index, bitsize_one_node);
if (!value.value)
/* If we are doing the bookkeeping for an element that was
directly output as a constructor, we must update
constructor_unfilled_index. */
constructor_unfilled_index = constructor_index;
}
else if (TREE_CODE (constructor_type) == VECTOR_TYPE)
{
tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type));
/* Do a basic check of initializer size. Note that vectors
always have a fixed size derived from their type. */
if (tree_int_cst_lt (constructor_max_index, constructor_index))
{
pedwarn_init ("excess elements in vector initializer");
break;
}
/* Now output the actual element. */
if (value.value)
output_init_element (value.value, strict_string,
elttype, constructor_index, 1);
constructor_index
= size_binop (PLUS_EXPR, constructor_index, bitsize_one_node);
if (!value.value)
/* If we are doing the bookkeeping for an element that was
directly output as a constructor, we must update
constructor_unfilled_index. */
constructor_unfilled_index = constructor_index;
}
/* Handle the sole element allowed in a braced initializer
for a scalar variable. */
else if (constructor_type != error_mark_node
&& constructor_fields == 0)
{
pedwarn_init ("excess elements in scalar initializer");
break;
}
else
{
if (value.value)
output_init_element (value.value, strict_string,
constructor_type, NULL_TREE, 1);
constructor_fields = 0;
}
/* Handle range initializers either at this level or anywhere higher
in the designator stack. */
if (constructor_range_stack)
{
struct constructor_range_stack *p, *range_stack;
int finish = 0;
range_stack = constructor_range_stack;
constructor_range_stack = 0;
while (constructor_stack != range_stack->stack)
{
gcc_assert (constructor_stack->implicit);
process_init_element (pop_init_level (1));
}
for (p = range_stack;
!p->range_end || tree_int_cst_equal (p->index, p->range_end);
p = p->prev)
{
gcc_assert (constructor_stack->implicit);
process_init_element (pop_init_level (1));
}
p->index = size_binop (PLUS_EXPR, p->index, bitsize_one_node);
if (tree_int_cst_equal (p->index, p->range_end) && !p->prev)
finish = 1;
while (1)
{
constructor_index = p->index;
constructor_fields = p->fields;
if (finish && p->range_end && p->index == p->range_start)
{
finish = 0;
p->prev = 0;
}
p = p->next;
if (!p)
break;
push_init_level (2);
p->stack = constructor_stack;
if (p->range_end && tree_int_cst_equal (p->index, p->range_end))
p->index = p->range_start;
}
if (!finish)
constructor_range_stack = range_stack;
continue;
}
break;
}
constructor_range_stack = 0;
}
/* Build a complete asm-statement, whose components are a CV_QUALIFIER
(guaranteed to be 'volatile' or null) and ARGS (represented using
an ASM_EXPR node). */
tree
build_asm_stmt (tree cv_qualifier, tree args)
{
if (!ASM_VOLATILE_P (args) && cv_qualifier)
ASM_VOLATILE_P (args) = 1;
return add_stmt (args);
}
/* Build an asm-expr, whose components are a STRING, some OUTPUTS,
some INPUTS, and some CLOBBERS. The latter three may be NULL.
SIMPLE indicates whether there was anything at all after the
string in the asm expression -- asm("blah") and asm("blah" : )
are subtly different. We use a ASM_EXPR node to represent this. */
tree
build_asm_expr (tree string, tree outputs, tree inputs, tree clobbers,
bool simple)
{
tree tail;
tree args;
int i;
const char *constraint;
const char **oconstraints;
bool allows_mem, allows_reg, is_inout;
int ninputs, noutputs;
ninputs = list_length (inputs);
noutputs = list_length (outputs);
oconstraints = (const char **) alloca (noutputs * sizeof (const char *));
string = resolve_asm_operand_names (string, outputs, inputs);
/* Remove output conversions that change the type but not the mode. */
for (i = 0, tail = outputs; tail; ++i, tail = TREE_CHAIN (tail))
{
tree output = TREE_VALUE (tail);
/* ??? Really, this should not be here. Users should be using a
proper lvalue, dammit. But there's a long history of using casts
in the output operands. In cases like longlong.h, this becomes a
primitive form of typechecking -- if the cast can be removed, then
the output operand had a type of the proper width; otherwise we'll
get an error. Gross, but ... */
STRIP_NOPS (output);
if (!lvalue_or_else (output, lv_asm))
output = error_mark_node;
if (output != error_mark_node
&& (TREE_READONLY (output)
|| TYPE_READONLY (TREE_TYPE (output))
|| ((TREE_CODE (TREE_TYPE (output)) == RECORD_TYPE
|| TREE_CODE (TREE_TYPE (output)) == UNION_TYPE)
&& C_TYPE_FIELDS_READONLY (TREE_TYPE (output)))))
readonly_error (output, lv_asm);
constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
oconstraints[i] = constraint;
if (parse_output_constraint (&constraint, i, ninputs, noutputs,
&allows_mem, &allows_reg, &is_inout))
{
/* If the operand is going to end up in memory,
mark it addressable. */
if (!allows_reg && !c_mark_addressable (output))
output = error_mark_node;
}
else
output = error_mark_node;
TREE_VALUE (tail) = output;
}
for (i = 0, tail = inputs; tail; ++i, tail = TREE_CHAIN (tail))
{
tree input;
constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
input = TREE_VALUE (tail);
if (parse_input_constraint (&constraint, i, ninputs, noutputs, 0,
oconstraints, &allows_mem, &allows_reg))
{
/* If the operand is going to end up in memory,
mark it addressable. */
if (!allows_reg && allows_mem)
{
/* Strip the nops as we allow this case. FIXME, this really
should be rejected or made deprecated. */
STRIP_NOPS (input);
if (!c_mark_addressable (input))
input = error_mark_node;
}
}
else
input = error_mark_node;
TREE_VALUE (tail) = input;
}
args = build_stmt (ASM_EXPR, string, outputs, inputs, clobbers);
/* asm statements without outputs, including simple ones, are treated
as volatile. */
ASM_INPUT_P (args) = simple;
ASM_VOLATILE_P (args) = (noutputs == 0);
return args;
}
/* Generate a goto statement to LABEL. */
tree
c_finish_goto_label (tree label)
{
tree decl = lookup_label (label);
if (!decl)
return NULL_TREE;
if (C_DECL_UNJUMPABLE_STMT_EXPR (decl))
{
error ("jump into statement expression");
return NULL_TREE;
}
if (C_DECL_UNJUMPABLE_VM (decl))
{
error ("jump into scope of identifier with variably modified type");
return NULL_TREE;
}
if (!C_DECL_UNDEFINABLE_STMT_EXPR (decl))
{
/* No jump from outside this statement expression context, so
record that there is a jump from within this context. */
struct c_label_list *nlist;
nlist = XOBNEW (&parser_obstack, struct c_label_list);
nlist->next = label_context_stack_se->labels_used;
nlist->label = decl;
label_context_stack_se->labels_used = nlist;
}
if (!C_DECL_UNDEFINABLE_VM (decl))
{
/* No jump from outside this context context of identifiers with
variably modified type, so record that there is a jump from
within this context. */
struct c_label_list *nlist;
nlist = XOBNEW (&parser_obstack, struct c_label_list);
nlist->next = label_context_stack_vm->labels_used;
nlist->label = decl;
label_context_stack_vm->labels_used = nlist;
}
TREE_USED (decl) = 1;
return add_stmt (build1 (GOTO_EXPR, void_type_node, decl));
}
/* Generate a computed goto statement to EXPR. */
tree
c_finish_goto_ptr (tree expr)
{
if (pedantic)
pedwarn ("ISO C forbids %<goto *expr;%>");
expr = convert (ptr_type_node, expr);
return add_stmt (build1 (GOTO_EXPR, void_type_node, expr));
}
/* Generate a C `return' statement. RETVAL is the expression for what
to return, or a null pointer for `return;' with no value. */
tree
c_finish_return (tree retval)
{
tree valtype = TREE_TYPE (TREE_TYPE (current_function_decl)), ret_stmt;
bool no_warning = false;
if (TREE_THIS_VOLATILE (current_function_decl))
warning (0, "function declared %<noreturn%> has a %<return%> statement");
if (!retval)
{
current_function_returns_null = 1;
if ((warn_return_type || flag_isoc99)
&& valtype != 0 && TREE_CODE (valtype) != VOID_TYPE)
{
pedwarn_c99 ("%<return%> with no value, in "
"function returning non-void");
no_warning = true;
}
}
else if (valtype == 0 || TREE_CODE (valtype) == VOID_TYPE)
{
current_function_returns_null = 1;
if (pedantic || TREE_CODE (TREE_TYPE (retval)) != VOID_TYPE)
pedwarn ("%<return%> with a value, in function returning void");
}
else
{
tree t = convert_for_assignment (valtype, retval, ic_return,
NULL_TREE, NULL_TREE, 0);
tree res = DECL_RESULT (current_function_decl);
tree inner;
current_function_returns_value = 1;
if (t == error_mark_node)
return NULL_TREE;
inner = t = convert (TREE_TYPE (res), t);
/* Strip any conversions, additions, and subtractions, and see if
we are returning the address of a local variable. Warn if so. */
while (1)
{
switch (TREE_CODE (inner))
{
case NOP_EXPR: case NON_LVALUE_EXPR: case CONVERT_EXPR:
case PLUS_EXPR:
inner = TREE_OPERAND (inner, 0);
continue;
case MINUS_EXPR:
/* If the second operand of the MINUS_EXPR has a pointer
type (or is converted from it), this may be valid, so
don't give a warning. */
{
tree op1 = TREE_OPERAND (inner, 1);
while (!POINTER_TYPE_P (TREE_TYPE (op1))
&& (TREE_CODE (op1) == NOP_EXPR
|| TREE_CODE (op1) == NON_LVALUE_EXPR
|| TREE_CODE (op1) == CONVERT_EXPR))
op1 = TREE_OPERAND (op1, 0);
if (POINTER_TYPE_P (TREE_TYPE (op1)))
break;
inner = TREE_OPERAND (inner, 0);
continue;
}
case ADDR_EXPR:
inner = TREE_OPERAND (inner, 0);
while (REFERENCE_CLASS_P (inner)
&& TREE_CODE (inner) != INDIRECT_REF)
inner = TREE_OPERAND (inner, 0);
if (DECL_P (inner)
&& !DECL_EXTERNAL (inner)
&& !TREE_STATIC (inner)
&& DECL_CONTEXT (inner) == current_function_decl)
warning (0, "function returns address of local variable");
break;
default:
break;
}
break;
}
retval = build2 (MODIFY_EXPR, TREE_TYPE (res), res, t);
}
ret_stmt = build_stmt (RETURN_EXPR, retval);
TREE_NO_WARNING (ret_stmt) |= no_warning;
return add_stmt (ret_stmt);
}
struct c_switch {
/* The SWITCH_EXPR being built. */
tree switch_expr;
/* The original type of the testing expression, i.e. before the
default conversion is applied. */
tree orig_type;
/* A splay-tree mapping the low element of a case range to the high
element, or NULL_TREE if there is no high element. Used to
determine whether or not a new case label duplicates an old case
label. We need a tree, rather than simply a hash table, because
of the GNU case range extension. */
splay_tree cases;
/* Number of nested statement expressions within this switch
statement; if nonzero, case and default labels may not
appear. */
unsigned int blocked_stmt_expr;
/* Scope of outermost declarations of identifiers with variably
modified type within this switch statement; if nonzero, case and
default labels may not appear. */
unsigned int blocked_vm;
/* The next node on the stack. */
struct c_switch *next;
};
/* A stack of the currently active switch statements. The innermost
switch statement is on the top of the stack. There is no need to
mark the stack for garbage collection because it is only active
during the processing of the body of a function, and we never
collect at that point. */
struct c_switch *c_switch_stack;
/* Start a C switch statement, testing expression EXP. Return the new
SWITCH_EXPR. */
tree
c_start_case (tree exp)
{
tree orig_type = error_mark_node;
struct c_switch *cs;
if (exp != error_mark_node)
{
orig_type = TREE_TYPE (exp);
if (!INTEGRAL_TYPE_P (orig_type))
{
if (orig_type != error_mark_node)
{
error ("switch quantity not an integer");
orig_type = error_mark_node;
}
exp = integer_zero_node;
}
else
{
tree type = TYPE_MAIN_VARIANT (orig_type);
if (!in_system_header
&& (type == long_integer_type_node
|| type == long_unsigned_type_node))
warning (OPT_Wtraditional, "%<long%> switch expression not "
"converted to %<int%> in ISO C");
exp = default_conversion (exp);
}
}
/* Add this new SWITCH_EXPR to the stack. */
cs = XNEW (struct c_switch);
cs->switch_expr = build3 (SWITCH_EXPR, orig_type, exp, NULL_TREE, NULL_TREE);
cs->orig_type = orig_type;
cs->cases = splay_tree_new (case_compare, NULL, NULL);
cs->blocked_stmt_expr = 0;
cs->blocked_vm = 0;
cs->next = c_switch_stack;
c_switch_stack = cs;
return add_stmt (cs->switch_expr);
}
/* Process a case label. */
tree
do_case (tree low_value, tree high_value)
{
tree label = NULL_TREE;
if (c_switch_stack && !c_switch_stack->blocked_stmt_expr
&& !c_switch_stack->blocked_vm)
{
label = c_add_case_label (c_switch_stack->cases,
SWITCH_COND (c_switch_stack->switch_expr),
c_switch_stack->orig_type,
low_value, high_value);
if (label == error_mark_node)
label = NULL_TREE;
}
else if (c_switch_stack && c_switch_stack->blocked_stmt_expr)
{
if (low_value)
error ("case label in statement expression not containing "
"enclosing switch statement");
else
error ("%<default%> label in statement expression not containing "
"enclosing switch statement");
}
else if (c_switch_stack && c_switch_stack->blocked_vm)
{
if (low_value)
error ("case label in scope of identifier with variably modified "
"type not containing enclosing switch statement");
else
error ("%<default%> label in scope of identifier with variably "
"modified type not containing enclosing switch statement");
}
else if (low_value)
error ("case label not within a switch statement");
else
error ("%<default%> label not within a switch statement");
return label;
}
/* Finish the switch statement. */
void
c_finish_case (tree body)
{
struct c_switch *cs = c_switch_stack;
location_t switch_location;
SWITCH_BODY (cs->switch_expr) = body;
/* We must not be within a statement expression nested in the switch
at this point; we might, however, be within the scope of an
identifier with variably modified type nested in the switch. */
gcc_assert (!cs->blocked_stmt_expr);
/* Emit warnings as needed. */
if (EXPR_HAS_LOCATION (cs->switch_expr))
switch_location = EXPR_LOCATION (cs->switch_expr);
else
switch_location = input_location;
c_do_switch_warnings (cs->cases, switch_location,
TREE_TYPE (cs->switch_expr),
SWITCH_COND (cs->switch_expr));
/* Pop the stack. */
c_switch_stack = cs->next;
splay_tree_delete (cs->cases);
XDELETE (cs);
}
/* Emit an if statement. IF_LOCUS is the location of the 'if'. COND,
THEN_BLOCK and ELSE_BLOCK are expressions to be used; ELSE_BLOCK
may be null. NESTED_IF is true if THEN_BLOCK contains another IF
statement, and was not surrounded with parenthesis. */
void
c_finish_if_stmt (location_t if_locus, tree cond, tree then_block,
tree else_block, bool nested_if)
{
tree stmt;
/* Diagnose an ambiguous else if if-then-else is nested inside if-then. */
if (warn_parentheses && nested_if && else_block == NULL)
{
tree inner_if = then_block;
/* We know from the grammar productions that there is an IF nested
within THEN_BLOCK. Due to labels and c99 conditional declarations,
it might not be exactly THEN_BLOCK, but should be the last
non-container statement within. */
while (1)
switch (TREE_CODE (inner_if))
{
case COND_EXPR:
goto found;
case BIND_EXPR:
inner_if = BIND_EXPR_BODY (inner_if);
break;
case STATEMENT_LIST:
inner_if = expr_last (then_block);
break;
case TRY_FINALLY_EXPR:
case TRY_CATCH_EXPR:
inner_if = TREE_OPERAND (inner_if, 0);
break;
default:
gcc_unreachable ();
}
found:
if (COND_EXPR_ELSE (inner_if))
warning (OPT_Wparentheses,
"%Hsuggest explicit braces to avoid ambiguous %<else%>",
&if_locus);
}
empty_body_warning (then_block, else_block);
stmt = build3 (COND_EXPR, void_type_node, cond, then_block, else_block);
SET_EXPR_LOCATION (stmt, if_locus);
add_stmt (stmt);
}
/* Emit a general-purpose loop construct. START_LOCUS is the location of
the beginning of the loop. COND is the loop condition. COND_IS_FIRST
is false for DO loops. INCR is the FOR increment expression. BODY is
the statement controlled by the loop. BLAB is the break label. CLAB is
the continue label. Everything is allowed to be NULL. */
void
c_finish_loop (location_t start_locus, tree cond, tree incr, tree body,
tree blab, tree clab, bool cond_is_first)
{
tree entry = NULL, exit = NULL, t;
/* If the condition is zero don't generate a loop construct. */
if (cond && integer_zerop (cond))
{
if (cond_is_first)
{
t = build_and_jump (&blab);
SET_EXPR_LOCATION (t, start_locus);
add_stmt (t);
}
}
else
{
tree top = build1 (LABEL_EXPR, void_type_node, NULL_TREE);
/* If we have an exit condition, then we build an IF with gotos either
out of the loop, or to the top of it. If there's no exit condition,
then we just build a jump back to the top. */
exit = build_and_jump (&LABEL_EXPR_LABEL (top));
if (cond && !integer_nonzerop (cond))
{
/* Canonicalize the loop condition to the end. This means
generating a branch to the loop condition. Reuse the
continue label, if possible. */
if (cond_is_first)
{
if (incr || !clab)
{
entry = build1 (LABEL_EXPR, void_type_node, NULL_TREE);
t = build_and_jump (&LABEL_EXPR_LABEL (entry));
}
else
t = build1 (GOTO_EXPR, void_type_node, clab);
SET_EXPR_LOCATION (t, start_locus);
add_stmt (t);
}
t = build_and_jump (&blab);
exit = fold_build3 (COND_EXPR, void_type_node, cond, exit, t);
if (cond_is_first)
SET_EXPR_LOCATION (exit, start_locus);
else
SET_EXPR_LOCATION (exit, input_location);
}
add_stmt (top);
}
if (body)
add_stmt (body);
if (clab)
add_stmt (build1 (LABEL_EXPR, void_type_node, clab));
if (incr)
add_stmt (incr);
if (entry)
add_stmt (entry);
if (exit)
add_stmt (exit);
if (blab)
add_stmt (build1 (LABEL_EXPR, void_type_node, blab));
}
tree
c_finish_bc_stmt (tree *label_p, bool is_break)
{
bool skip;
tree label = *label_p;
/* In switch statements break is sometimes stylistically used after
a return statement. This can lead to spurious warnings about
control reaching the end of a non-void function when it is
inlined. Note that we are calling block_may_fallthru with
language specific tree nodes; this works because
block_may_fallthru returns true when given something it does not
understand. */
skip = !block_may_fallthru (cur_stmt_list);
if (!label)
{
if (!skip)
*label_p = label = create_artificial_label ();
}
else if (TREE_CODE (label) == LABEL_DECL)
;
else switch (TREE_INT_CST_LOW (label))
{
case 0:
if (is_break)
error ("break statement not within loop or switch");
else
error ("continue statement not within a loop");
return NULL_TREE;
case 1:
gcc_assert (is_break);
error ("break statement used with OpenMP for loop");
return NULL_TREE;
default:
gcc_unreachable ();
}
if (skip)
return NULL_TREE;
return add_stmt (build1 (GOTO_EXPR, void_type_node, label));
}
/* A helper routine for c_process_expr_stmt and c_finish_stmt_expr. */
static void
emit_side_effect_warnings (tree expr)
{
if (expr == error_mark_node)
;
else if (!TREE_SIDE_EFFECTS (expr))
{
if (!VOID_TYPE_P (TREE_TYPE (expr)) && !TREE_NO_WARNING (expr))
warning (0, "%Hstatement with no effect",
EXPR_HAS_LOCATION (expr) ? EXPR_LOCUS (expr) : &input_location);
}
else if (warn_unused_value)
warn_if_unused_value (expr, input_location);
}
/* Process an expression as if it were a complete statement. Emit
diagnostics, but do not call ADD_STMT. */
tree
c_process_expr_stmt (tree expr)
{
if (!expr)
return NULL_TREE;
if (warn_sequence_point)
verify_sequence_points (expr);
if (TREE_TYPE (expr) != error_mark_node
&& !COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (expr))
&& TREE_CODE (TREE_TYPE (expr)) != ARRAY_TYPE)
error ("expression statement has incomplete type");
/* If we're not processing a statement expression, warn about unused values.
Warnings for statement expressions will be emitted later, once we figure
out which is the result. */
if (!STATEMENT_LIST_STMT_EXPR (cur_stmt_list)
&& (extra_warnings || warn_unused_value))
emit_side_effect_warnings (expr);
/* If the expression is not of a type to which we cannot assign a line
number, wrap the thing in a no-op NOP_EXPR. */
if (DECL_P (expr) || CONSTANT_CLASS_P (expr))
expr = build1 (NOP_EXPR, TREE_TYPE (expr), expr);
if (EXPR_P (expr))
SET_EXPR_LOCATION (expr, input_location);
return expr;
}
/* Emit an expression as a statement. */
tree
c_finish_expr_stmt (tree expr)
{
if (expr)
return add_stmt (c_process_expr_stmt (expr));
else
return NULL;
}
/* Do the opposite and emit a statement as an expression. To begin,
create a new binding level and return it. */
tree
c_begin_stmt_expr (void)
{
tree ret;
struct c_label_context_se *nstack;
struct c_label_list *glist;
/* We must force a BLOCK for this level so that, if it is not expanded
later, there is a way to turn off the entire subtree of blocks that
are contained in it. */
keep_next_level ();
ret = c_begin_compound_stmt (true);
if (c_switch_stack)
{
c_switch_stack->blocked_stmt_expr++;
gcc_assert (c_switch_stack->blocked_stmt_expr != 0);
}
for (glist = label_context_stack_se->labels_used;
glist != NULL;
glist = glist->next)
{
C_DECL_UNDEFINABLE_STMT_EXPR (glist->label) = 1;
}
nstack = XOBNEW (&parser_obstack, struct c_label_context_se);
nstack->labels_def = NULL;
nstack->labels_used = NULL;
nstack->next = label_context_stack_se;
label_context_stack_se = nstack;
/* Mark the current statement list as belonging to a statement list. */
STATEMENT_LIST_STMT_EXPR (ret) = 1;
return ret;
}
tree
c_finish_stmt_expr (tree body)
{
tree last, type, tmp, val;
tree *last_p;
struct c_label_list *dlist, *glist, *glist_prev = NULL;
body = c_end_compound_stmt (body, true);
if (c_switch_stack)
{
gcc_assert (c_switch_stack->blocked_stmt_expr != 0);
c_switch_stack->blocked_stmt_expr--;
}
/* It is no longer possible to jump to labels defined within this
statement expression. */
for (dlist = label_context_stack_se->labels_def;
dlist != NULL;
dlist = dlist->next)
{
C_DECL_UNJUMPABLE_STMT_EXPR (dlist->label) = 1;
}
/* It is again possible to define labels with a goto just outside
this statement expression. */
for (glist = label_context_stack_se->next->labels_used;
glist != NULL;
glist = glist->next)
{
C_DECL_UNDEFINABLE_STMT_EXPR (glist->label) = 0;
glist_prev = glist;
}
if (glist_prev != NULL)
glist_prev->next = label_context_stack_se->labels_used;
else
label_context_stack_se->next->labels_used
= label_context_stack_se->labels_used;
label_context_stack_se = label_context_stack_se->next;
/* Locate the last statement in BODY. See c_end_compound_stmt
about always returning a BIND_EXPR. */
last_p = &BIND_EXPR_BODY (body);
last = BIND_EXPR_BODY (body);
continue_searching:
if (TREE_CODE (last) == STATEMENT_LIST)
{
tree_stmt_iterator i;
/* This can happen with degenerate cases like ({ }). No value. */
if (!TREE_SIDE_EFFECTS (last))
return body;
/* If we're supposed to generate side effects warnings, process
all of the statements except the last. */
if (extra_warnings || warn_unused_value)
{
for (i = tsi_start (last); !tsi_one_before_end_p (i); tsi_next (&i))
emit_side_effect_warnings (tsi_stmt (i));
}
else
i = tsi_last (last);
last_p = tsi_stmt_ptr (i);
last = *last_p;
}
/* If the end of the list is exception related, then the list was split
by a call to push_cleanup. Continue searching. */
if (TREE_CODE (last) == TRY_FINALLY_EXPR
|| TREE_CODE (last) == TRY_CATCH_EXPR)
{
last_p = &TREE_OPERAND (last, 0);
last = *last_p;
goto continue_searching;
}
/* In the case that the BIND_EXPR is not necessary, return the
expression out from inside it. */
if (last == error_mark_node
|| (last == BIND_EXPR_BODY (body)
&& BIND_EXPR_VARS (body) == NULL))
{
/* Do not warn if the return value of a statement expression is
unused. */
if (EXPR_P (last))
TREE_NO_WARNING (last) = 1;
return last;
}
/* Extract the type of said expression. */
type = TREE_TYPE (last);
/* If we're not returning a value at all, then the BIND_EXPR that
we already have is a fine expression to return. */
if (!type || VOID_TYPE_P (type))
return body;
/* Now that we've located the expression containing the value, it seems
silly to make voidify_wrapper_expr repeat the process. Create a
temporary of the appropriate type and stick it in a TARGET_EXPR. */
tmp = create_tmp_var_raw (type, NULL);
/* Unwrap a no-op NOP_EXPR as added by c_finish_expr_stmt. This avoids
tree_expr_nonnegative_p giving up immediately. */
val = last;
if (TREE_CODE (val) == NOP_EXPR
&& TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0)))
val = TREE_OPERAND (val, 0);
*last_p = build2 (MODIFY_EXPR, void_type_node, tmp, val);
SET_EXPR_LOCUS (*last_p, EXPR_LOCUS (last));
return build4 (TARGET_EXPR, type, tmp, body, NULL_TREE, NULL_TREE);
}
/* Begin the scope of an identifier of variably modified type, scope
number SCOPE. Jumping from outside this scope to inside it is not
permitted. */
void
c_begin_vm_scope (unsigned int scope)
{
struct c_label_context_vm *nstack;
struct c_label_list *glist;
gcc_assert (scope > 0);
/* At file_scope, we don't have to do any processing. */
if (label_context_stack_vm == NULL)
return;
if (c_switch_stack && !c_switch_stack->blocked_vm)
c_switch_stack->blocked_vm = scope;
for (glist = label_context_stack_vm->labels_used;
glist != NULL;
glist = glist->next)
{
C_DECL_UNDEFINABLE_VM (glist->label) = 1;
}
nstack = XOBNEW (&parser_obstack, struct c_label_context_vm);
nstack->labels_def = NULL;
nstack->labels_used = NULL;
nstack->scope = scope;
nstack->next = label_context_stack_vm;
label_context_stack_vm = nstack;
}
/* End a scope which may contain identifiers of variably modified
type, scope number SCOPE. */
void
c_end_vm_scope (unsigned int scope)
{
if (label_context_stack_vm == NULL)
return;
if (c_switch_stack && c_switch_stack->blocked_vm == scope)
c_switch_stack->blocked_vm = 0;
/* We may have a number of nested scopes of identifiers with
variably modified type, all at this depth. Pop each in turn. */
while (label_context_stack_vm->scope == scope)
{
struct c_label_list *dlist, *glist, *glist_prev = NULL;
/* It is no longer possible to jump to labels defined within this
scope. */
for (dlist = label_context_stack_vm->labels_def;
dlist != NULL;
dlist = dlist->next)
{
C_DECL_UNJUMPABLE_VM (dlist->label) = 1;
}
/* It is again possible to define labels with a goto just outside
this scope. */
for (glist = label_context_stack_vm->next->labels_used;
glist != NULL;
glist = glist->next)
{
C_DECL_UNDEFINABLE_VM (glist->label) = 0;
glist_prev = glist;
}
if (glist_prev != NULL)
glist_prev->next = label_context_stack_vm->labels_used;
else
label_context_stack_vm->next->labels_used
= label_context_stack_vm->labels_used;
label_context_stack_vm = label_context_stack_vm->next;
}
}
/* Begin and end compound statements. This is as simple as pushing
and popping new statement lists from the tree. */
tree
c_begin_compound_stmt (bool do_scope)
{
tree stmt = push_stmt_list ();
if (do_scope)
push_scope ();
return stmt;
}
tree
c_end_compound_stmt (tree stmt, bool do_scope)
{
tree block = NULL;
if (do_scope)
{
if (c_dialect_objc ())
objc_clear_super_receiver ();
block = pop_scope ();
}
stmt = pop_stmt_list (stmt);
stmt = c_build_bind_expr (block, stmt);
/* If this compound statement is nested immediately inside a statement
expression, then force a BIND_EXPR to be created. Otherwise we'll
do the wrong thing for ({ { 1; } }) or ({ 1; { } }). In particular,
STATEMENT_LISTs merge, and thus we can lose track of what statement
was really last. */
if (cur_stmt_list
&& STATEMENT_LIST_STMT_EXPR (cur_stmt_list)
&& TREE_CODE (stmt) != BIND_EXPR)
{
stmt = build3 (BIND_EXPR, void_type_node, NULL, stmt, NULL);
TREE_SIDE_EFFECTS (stmt) = 1;
}
return stmt;
}
/* Queue a cleanup. CLEANUP is an expression/statement to be executed
when the current scope is exited. EH_ONLY is true when this is not
meant to apply to normal control flow transfer. */
void
push_cleanup (tree ARG_UNUSED (decl), tree cleanup, bool eh_only)
{
enum tree_code code;
tree stmt, list;
bool stmt_expr;
code = eh_only ? TRY_CATCH_EXPR : TRY_FINALLY_EXPR;
stmt = build_stmt (code, NULL, cleanup);
add_stmt (stmt);
stmt_expr = STATEMENT_LIST_STMT_EXPR (cur_stmt_list);
list = push_stmt_list ();
TREE_OPERAND (stmt, 0) = list;
STATEMENT_LIST_STMT_EXPR (list) = stmt_expr;
}
/* Build a binary-operation expression without default conversions.
CODE is the kind of expression to build.
This function differs from `build' in several ways:
the data type of the result is computed and recorded in it,
warnings are generated if arg data types are invalid,
special handling for addition and subtraction of pointers is known,
and some optimization is done (operations on narrow ints
are done in the narrower type when that gives the same result).
Constant folding is also done before the result is returned.
Note that the operands will never have enumeral types, or function
or array types, because either they will have the default conversions
performed or they have both just been converted to some other type in which
the arithmetic is to be done. */
tree
build_binary_op (enum tree_code code, tree orig_op0, tree orig_op1,
int convert_p)
{
tree type0, type1;
enum tree_code code0, code1;
tree op0, op1;
const char *invalid_op_diag;
/* Expression code to give to the expression when it is built.
Normally this is CODE, which is what the caller asked for,
but in some special cases we change it. */
enum tree_code resultcode = code;
/* Data type in which the computation is to be performed.
In the simplest cases this is the common type of the arguments. */
tree result_type = NULL;
/* Nonzero means operands have already been type-converted
in whatever way is necessary.
Zero means they need to be converted to RESULT_TYPE. */
int converted = 0;
/* Nonzero means create the expression with this type, rather than
RESULT_TYPE. */
tree build_type = 0;
/* Nonzero means after finally constructing the expression
convert it to this type. */
tree final_type = 0;
/* Nonzero if this is an operation like MIN or MAX which can
safely be computed in short if both args are promoted shorts.
Also implies COMMON.
-1 indicates a bitwise operation; this makes a difference
in the exact conditions for when it is safe to do the operation
in a narrower mode. */
int shorten = 0;
/* Nonzero if this is a comparison operation;
if both args are promoted shorts, compare the original shorts.
Also implies COMMON. */
int short_compare = 0;
/* Nonzero if this is a right-shift operation, which can be computed on the
original short and then promoted if the operand is a promoted short. */
int short_shift = 0;
/* Nonzero means set RESULT_TYPE to the common type of the args. */
int common = 0;
/* True means types are compatible as far as ObjC is concerned. */
bool objc_ok;
if (convert_p)
{
op0 = default_conversion (orig_op0);
op1 = default_conversion (orig_op1);
}
else
{
op0 = orig_op0;
op1 = orig_op1;
}
type0 = TREE_TYPE (op0);
type1 = TREE_TYPE (op1);
/* The expression codes of the data types of the arguments tell us
whether the arguments are integers, floating, pointers, etc. */
code0 = TREE_CODE (type0);
code1 = TREE_CODE (type1);
/* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */
STRIP_TYPE_NOPS (op0);
STRIP_TYPE_NOPS (op1);
/* If an error was already reported for one of the arguments,
avoid reporting another error. */
if (code0 == ERROR_MARK || code1 == ERROR_MARK)
return error_mark_node;
if ((invalid_op_diag
= targetm.invalid_binary_op (code, type0, type1)))
{
error (invalid_op_diag);
return error_mark_node;
}
objc_ok = objc_compare_types (type0, type1, -3, NULL_TREE);
switch (code)
{
case PLUS_EXPR:
/* Handle the pointer + int case. */
if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
return pointer_int_sum (PLUS_EXPR, op0, op1);
else if (code1 == POINTER_TYPE && code0 == INTEGER_TYPE)
return pointer_int_sum (PLUS_EXPR, op1, op0);
else
common = 1;
break;
case MINUS_EXPR:
/* Subtraction of two similar pointers.
We must subtract them as integers, then divide by object size. */
if (code0 == POINTER_TYPE && code1 == POINTER_TYPE
&& comp_target_types (type0, type1))
return pointer_diff (op0, op1);
/* Handle pointer minus int. Just like pointer plus int. */
else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
return pointer_int_sum (MINUS_EXPR, op0, op1);
else
common = 1;
break;
case MULT_EXPR:
common = 1;
break;
case TRUNC_DIV_EXPR:
case CEIL_DIV_EXPR:
case FLOOR_DIV_EXPR:
case ROUND_DIV_EXPR:
case EXACT_DIV_EXPR:
/* Floating point division by zero is a legitimate way to obtain
infinities and NaNs. */
if (skip_evaluation == 0 && integer_zerop (op1))
warning (OPT_Wdiv_by_zero, "division by zero");
if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
|| code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE)
&& (code1 == INTEGER_TYPE || code1 == REAL_TYPE
|| code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE))
{
enum tree_code tcode0 = code0, tcode1 = code1;
if (code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE)
tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0)));
if (code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE)
tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1)));
if (!(tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE))
resultcode = RDIV_EXPR;
else
/* Although it would be tempting to shorten always here, that
loses on some targets, since the modulo instruction is
undefined if the quotient can't be represented in the
computation mode. We shorten only if unsigned or if
dividing by something we know != -1. */
shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0))
|| (TREE_CODE (op1) == INTEGER_CST
&& !integer_all_onesp (op1)));
common = 1;
}
break;
case BIT_AND_EXPR:
case BIT_IOR_EXPR:
case BIT_XOR_EXPR:
if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
shorten = -1;
else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE)
common = 1;
break;
case TRUNC_MOD_EXPR:
case FLOOR_MOD_EXPR:
if (skip_evaluation == 0 && integer_zerop (op1))
warning (OPT_Wdiv_by_zero, "division by zero");
if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
{
/* Although it would be tempting to shorten always here, that loses
on some targets, since the modulo instruction is undefined if the
quotient can't be represented in the computation mode. We shorten
only if unsigned or if dividing by something we know != -1. */
shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0))
|| (TREE_CODE (op1) == INTEGER_CST
&& !integer_all_onesp (op1)));
common = 1;
}
break;
case TRUTH_ANDIF_EXPR:
case TRUTH_ORIF_EXPR:
case TRUTH_AND_EXPR:
case TRUTH_OR_EXPR:
case TRUTH_XOR_EXPR:
if ((code0 == INTEGER_TYPE || code0 == POINTER_TYPE
|| code0 == REAL_TYPE || code0 == COMPLEX_TYPE)
&& (code1 == INTEGER_TYPE || code1 == POINTER_TYPE
|| code1 == REAL_TYPE || code1 == COMPLEX_TYPE))
{
/* Result of these operations is always an int,
but that does not mean the operands should be
converted to ints! */
result_type = integer_type_node;
op0 = c_common_truthvalue_conversion (op0);
op1 = c_common_truthvalue_conversion (op1);
converted = 1;
}
break;
/* Shift operations: result has same type as first operand;
always convert second operand to int.
Also set SHORT_SHIFT if shifting rightward. */
case RSHIFT_EXPR:
if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
{
if (TREE_CODE (op1) == INTEGER_CST && skip_evaluation == 0)
{
if (tree_int_cst_sgn (op1) < 0)
warning (0, "right shift count is negative");
else
{
if (!integer_zerop (op1))
short_shift = 1;
if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
warning (0, "right shift count >= width of type");
}
}
/* Use the type of the value to be shifted. */
result_type = type0;
/* Convert the shift-count to an integer, regardless of size
of value being shifted. */
if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
op1 = convert (integer_type_node, op1);
/* Avoid converting op1 to result_type later. */
converted = 1;
}
break;
case LSHIFT_EXPR:
if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
{
if (TREE_CODE (op1) == INTEGER_CST && skip_evaluation == 0)
{
if (tree_int_cst_sgn (op1) < 0)
warning (0, "left shift count is negative");
else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
warning (0, "left shift count >= width of type");
}
/* Use the type of the value to be shifted. */
result_type = type0;
/* Convert the shift-count to an integer, regardless of size
of value being shifted. */
if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
op1 = convert (integer_type_node, op1);
/* Avoid converting op1 to result_type later. */
converted = 1;
}
break;
case EQ_EXPR:
case NE_EXPR:
if (code0 == REAL_TYPE || code1 == REAL_TYPE)
warning (OPT_Wfloat_equal,
"comparing floating point with == or != is unsafe");
/* Result of comparison is always int,
but don't convert the args to int! */
build_type = integer_type_node;
if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
|| code0 == COMPLEX_TYPE)
&& (code1 == INTEGER_TYPE || code1 == REAL_TYPE
|| code1 == COMPLEX_TYPE))
short_compare = 1;
else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
{
tree tt0 = TREE_TYPE (type0);
tree tt1 = TREE_TYPE (type1);
/* Anything compares with void *. void * compares with anything.
Otherwise, the targets must be compatible
and both must be object or both incomplete. */
if (comp_target_types (type0, type1))
result_type = common_pointer_type (type0, type1);
else if (VOID_TYPE_P (tt0))
{
/* op0 != orig_op0 detects the case of something
whose value is 0 but which isn't a valid null ptr const. */
if (pedantic && !null_pointer_constant_p (orig_op0)
&& TREE_CODE (tt1) == FUNCTION_TYPE)
pedwarn ("ISO C forbids comparison of %<void *%>"
" with function pointer");
}
else if (VOID_TYPE_P (tt1))
{
if (pedantic && !null_pointer_constant_p (orig_op1)
&& TREE_CODE (tt0) == FUNCTION_TYPE)
pedwarn ("ISO C forbids comparison of %<void *%>"
" with function pointer");
}
else
/* Avoid warning about the volatile ObjC EH puts on decls. */
if (!objc_ok)
pedwarn ("comparison of distinct pointer types lacks a cast");
if (result_type == NULL_TREE)
result_type = ptr_type_node;
}
else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1))
{
if (TREE_CODE (op0) == ADDR_EXPR
&& DECL_P (TREE_OPERAND (op0, 0))
&& (TREE_CODE (TREE_OPERAND (op0, 0)) == PARM_DECL
|| TREE_CODE (TREE_OPERAND (op0, 0)) == LABEL_DECL
|| !DECL_WEAK (TREE_OPERAND (op0, 0))))
warning (OPT_Waddress, "the address of %qD will never be NULL",
TREE_OPERAND (op0, 0));
result_type = type0;
}
else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0))
{
if (TREE_CODE (op1) == ADDR_EXPR
&& DECL_P (TREE_OPERAND (op1, 0))
&& (TREE_CODE (TREE_OPERAND (op1, 0)) == PARM_DECL
|| TREE_CODE (TREE_OPERAND (op1, 0)) == LABEL_DECL
|| !DECL_WEAK (TREE_OPERAND (op1, 0))))
warning (OPT_Waddress, "the address of %qD will never be NULL",
TREE_OPERAND (op1, 0));
result_type = type1;
}
else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
{
result_type = type0;
pedwarn ("comparison between pointer and integer");
}
else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
{
result_type = type1;
pedwarn ("comparison between pointer and integer");
}
break;
case LE_EXPR:
case GE_EXPR:
case LT_EXPR:
case GT_EXPR:
build_type = integer_type_node;
if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE)
&& (code1 == INTEGER_TYPE || code1 == REAL_TYPE))
short_compare = 1;
else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
{
if (comp_target_types (type0, type1))
{
result_type = common_pointer_type (type0, type1);
if (!COMPLETE_TYPE_P (TREE_TYPE (type0))
!= !COMPLETE_TYPE_P (TREE_TYPE (type1)))
pedwarn ("comparison of complete and incomplete pointers");
else if (pedantic
&& TREE_CODE (TREE_TYPE (type0)) == FUNCTION_TYPE)
pedwarn ("ISO C forbids ordered comparisons of pointers to functions");
}
else
{
result_type = ptr_type_node;
pedwarn ("comparison of distinct pointer types lacks a cast");
}
}
else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1))
{
result_type = type0;
if (pedantic || extra_warnings)
pedwarn ("ordered comparison of pointer with integer zero");
}
else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0))
{
result_type = type1;
if (pedantic)
pedwarn ("ordered comparison of pointer with integer zero");
}
else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
{
result_type = type0;
pedwarn ("comparison between pointer and integer");
}
else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
{
result_type = type1;
pedwarn ("comparison between pointer and integer");
}
break;
default:
gcc_unreachable ();
}
if (code0 == ERROR_MARK || code1 == ERROR_MARK)
return error_mark_node;
if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE
&& (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1))
|| !same_scalar_type_ignoring_signedness (TREE_TYPE (type0),
TREE_TYPE (type1))))
{
binary_op_error (code);
return error_mark_node;
}
if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE
|| code0 == VECTOR_TYPE)
&&
(code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE
|| code1 == VECTOR_TYPE))
{
int none_complex = (code0 != COMPLEX_TYPE && code1 != COMPLEX_TYPE);
if (shorten || common || short_compare)
result_type = c_common_type (type0, type1);
/* For certain operations (which identify themselves by shorten != 0)
if both args were extended from the same smaller type,
do the arithmetic in that type and then extend.
shorten !=0 and !=1 indicates a bitwise operation.
For them, this optimization is safe only if
both args are zero-extended or both are sign-extended.
Otherwise, we might change the result.
Eg, (short)-1 | (unsigned short)-1 is (int)-1
but calculated in (unsigned short) it would be (unsigned short)-1. */
if (shorten && none_complex)
{
int unsigned0, unsigned1;
tree arg0, arg1;
int uns;
tree type;
/* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
excessive narrowing when we call get_narrower below. For
example, suppose that OP0 is of unsigned int extended
from signed char and that RESULT_TYPE is long long int.
If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
like
(long long int) (unsigned int) signed_char
which get_narrower would narrow down to
(unsigned int) signed char
If we do not cast OP0 first, get_narrower would return
signed_char, which is inconsistent with the case of the
explicit cast. */
op0 = convert (result_type, op0);
op1 = convert (result_type, op1);
arg0 = get_narrower (op0, &unsigned0);
arg1 = get_narrower (op1, &unsigned1);
/* UNS is 1 if the operation to be done is an unsigned one. */
uns = TYPE_UNSIGNED (result_type);
final_type = result_type;
/* Handle the case that OP0 (or OP1) does not *contain* a conversion
but it *requires* conversion to FINAL_TYPE. */
if ((TYPE_PRECISION (TREE_TYPE (op0))
== TYPE_PRECISION (TREE_TYPE (arg0)))
&& TREE_TYPE (op0) != final_type)
unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
if ((TYPE_PRECISION (TREE_TYPE (op1))
== TYPE_PRECISION (TREE_TYPE (arg1)))
&& TREE_TYPE (op1) != final_type)
unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
/* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
/* For bitwise operations, signedness of nominal type
does not matter. Consider only how operands were extended. */
if (shorten == -1)
uns = unsigned0;
/* Note that in all three cases below we refrain from optimizing
an unsigned operation on sign-extended args.
That would not be valid. */
/* Both args variable: if both extended in same way
from same width, do it in that width.
Do it unsigned if args were zero-extended. */
if ((TYPE_PRECISION (TREE_TYPE (arg0))
< TYPE_PRECISION (result_type))
&& (TYPE_PRECISION (TREE_TYPE (arg1))
== TYPE_PRECISION (TREE_TYPE (arg0)))
&& unsigned0 == unsigned1
&& (unsigned0 || !uns))
result_type
= c_common_signed_or_unsigned_type
(unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
else if (TREE_CODE (arg0) == INTEGER_CST
&& (unsigned1 || !uns)
&& (TYPE_PRECISION (TREE_TYPE (arg1))
< TYPE_PRECISION (result_type))
&& (type
= c_common_signed_or_unsigned_type (unsigned1,
TREE_TYPE (arg1)),
int_fits_type_p (arg0, type)))
result_type = type;
else if (TREE_CODE (arg1) == INTEGER_CST
&& (unsigned0 || !uns)
&& (TYPE_PRECISION (TREE_TYPE (arg0))
< TYPE_PRECISION (result_type))
&& (type
= c_common_signed_or_unsigned_type (unsigned0,
TREE_TYPE (arg0)),
int_fits_type_p (arg1, type)))
result_type = type;
}
/* Shifts can be shortened if shifting right. */
if (short_shift)
{
int unsigned_arg;
tree arg0 = get_narrower (op0, &unsigned_arg);
final_type = result_type;
if (arg0 == op0 && final_type == TREE_TYPE (op0))
unsigned_arg = TYPE_UNSIGNED (TREE_TYPE (op0));
if (TYPE_PRECISION (TREE_TYPE (arg0)) < TYPE_PRECISION (result_type)
/* We can shorten only if the shift count is less than the
number of bits in the smaller type size. */
&& compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (arg0))) < 0
/* We cannot drop an unsigned shift after sign-extension. */
&& (!TYPE_UNSIGNED (final_type) || unsigned_arg))
{
/* Do an unsigned shift if the operand was zero-extended. */
result_type
= c_common_signed_or_unsigned_type (unsigned_arg,
TREE_TYPE (arg0));
/* Convert value-to-be-shifted to that type. */
if (TREE_TYPE (op0) != result_type)
op0 = convert (result_type, op0);
converted = 1;
}
}
/* Comparison operations are shortened too but differently.
They identify themselves by setting short_compare = 1. */
if (short_compare)
{
/* Don't write &op0, etc., because that would prevent op0
from being kept in a register.
Instead, make copies of the our local variables and
pass the copies by reference, then copy them back afterward. */
tree xop0 = op0, xop1 = op1, xresult_type = result_type;
enum tree_code xresultcode = resultcode;
tree val
= shorten_compare (&xop0, &xop1, &xresult_type, &xresultcode);
if (val != 0)
return val;
op0 = xop0, op1 = xop1;
converted = 1;
resultcode = xresultcode;
if (warn_sign_compare && skip_evaluation == 0)
{
int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
int unsignedp0, unsignedp1;
tree primop0 = get_narrower (op0, &unsignedp0);
tree primop1 = get_narrower (op1, &unsignedp1);
xop0 = orig_op0;
xop1 = orig_op1;
STRIP_TYPE_NOPS (xop0);
STRIP_TYPE_NOPS (xop1);
/* Give warnings for comparisons between signed and unsigned
quantities that may fail.
Do the checking based on the original operand trees, so that
casts will be considered, but default promotions won't be.
Do not warn if the comparison is being done in a signed type,
since the signed type will only be chosen if it can represent
all the values of the unsigned type. */
if (!TYPE_UNSIGNED (result_type))
/* OK */;
/* Do not warn if both operands are the same signedness. */
else if (op0_signed == op1_signed)
/* OK */;
else
{
tree sop, uop;
bool ovf;
if (op0_signed)
sop = xop0, uop = xop1;
else
sop = xop1, uop = xop0;
/* Do not warn if the signed quantity is an
unsuffixed integer literal (or some static
constant expression involving such literals or a
conditional expression involving such literals)
and it is non-negative. */
if (tree_expr_nonnegative_warnv_p (sop, &ovf))
/* OK */;
/* Do not warn if the comparison is an equality operation,
the unsigned quantity is an integral constant, and it
would fit in the result if the result were signed. */
else if (TREE_CODE (uop) == INTEGER_CST
&& (resultcode == EQ_EXPR || resultcode == NE_EXPR)
&& int_fits_type_p
(uop, c_common_signed_type (result_type)))
/* OK */;
/* Do not warn if the unsigned quantity is an enumeration
constant and its maximum value would fit in the result
if the result were signed. */
else if (TREE_CODE (uop) == INTEGER_CST
&& TREE_CODE (TREE_TYPE (uop)) == ENUMERAL_TYPE
&& int_fits_type_p
(TYPE_MAX_VALUE (TREE_TYPE (uop)),
c_common_signed_type (result_type)))
/* OK */;
else
warning (0, "comparison between signed and unsigned");
}
/* Warn if two unsigned values are being compared in a size
larger than their original size, and one (and only one) is the
result of a `~' operator. This comparison will always fail.
Also warn if one operand is a constant, and the constant
does not have all bits set that are set in the ~ operand
when it is extended. */
if ((TREE_CODE (primop0) == BIT_NOT_EXPR)
!= (TREE_CODE (primop1) == BIT_NOT_EXPR))
{
if (TREE_CODE (primop0) == BIT_NOT_EXPR)
primop0 = get_narrower (TREE_OPERAND (primop0, 0),
&unsignedp0);
else
primop1 = get_narrower (TREE_OPERAND (primop1, 0),
&unsignedp1);
if (host_integerp (primop0, 0) || host_integerp (primop1, 0))
{
tree primop;
HOST_WIDE_INT constant, mask;
int unsignedp, bits;
if (host_integerp (primop0, 0))
{
primop = primop1;
unsignedp = unsignedp1;
constant = tree_low_cst (primop0, 0);
}
else
{
primop = primop0;
unsignedp = unsignedp0;
constant = tree_low_cst (primop1, 0);
}
bits = TYPE_PRECISION (TREE_TYPE (primop));
if (bits < TYPE_PRECISION (result_type)
&& bits < HOST_BITS_PER_WIDE_INT && unsignedp)
{
mask = (~(HOST_WIDE_INT) 0) << bits;
if ((mask & constant) != mask)
warning (0, "comparison of promoted ~unsigned with constant");
}
}
else if (unsignedp0 && unsignedp1
&& (TYPE_PRECISION (TREE_TYPE (primop0))
< TYPE_PRECISION (result_type))
&& (TYPE_PRECISION (TREE_TYPE (primop1))
< TYPE_PRECISION (result_type)))
warning (0, "comparison of promoted ~unsigned with unsigned");
}
}
}
}
/* At this point, RESULT_TYPE must be nonzero to avoid an error message.
If CONVERTED is zero, both args will be converted to type RESULT_TYPE.
Then the expression will be built.
It will be given type FINAL_TYPE if that is nonzero;
otherwise, it will be given type RESULT_TYPE. */
if (!result_type)
{
binary_op_error (code);
return error_mark_node;
}
if (!converted)
{
if (TREE_TYPE (op0) != result_type)
op0 = convert_and_check (result_type, op0);
if (TREE_TYPE (op1) != result_type)
op1 = convert_and_check (result_type, op1);
/* This can happen if one operand has a vector type, and the other
has a different type. */
if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK)
return error_mark_node;
}
if (build_type == NULL_TREE)
build_type = result_type;
{
/* Treat expressions in initializers specially as they can't trap. */
tree result = require_constant_value ? fold_build2_initializer (resultcode,
build_type,
op0, op1)
: fold_build2 (resultcode, build_type,
op0, op1);
if (final_type != 0)
result = convert (final_type, result);
return result;
}
}
/* Convert EXPR to be a truth-value, validating its type for this
purpose. */
tree
c_objc_common_truthvalue_conversion (tree expr)
{
switch (TREE_CODE (TREE_TYPE (expr)))
{
case ARRAY_TYPE:
error ("used array that cannot be converted to pointer where scalar is required");
return error_mark_node;
case RECORD_TYPE:
error ("used struct type value where scalar is required");
return error_mark_node;
case UNION_TYPE:
error ("used union type value where scalar is required");
return error_mark_node;
case FUNCTION_TYPE:
gcc_unreachable ();
default:
break;
}
/* ??? Should we also give an error for void and vectors rather than
leaving those to give errors later? */
return c_common_truthvalue_conversion (expr);
}
/* Convert EXPR to a contained DECL, updating *TC, *TI and *SE as
required. */
tree
c_expr_to_decl (tree expr, bool *tc ATTRIBUTE_UNUSED,
bool *ti ATTRIBUTE_UNUSED, bool *se)
{
if (TREE_CODE (expr) == COMPOUND_LITERAL_EXPR)
{
tree decl = COMPOUND_LITERAL_EXPR_DECL (expr);
/* Executing a compound literal inside a function reinitializes
it. */
if (!TREE_STATIC (decl))
*se = true;
return decl;
}
else
return expr;
}
/* Like c_begin_compound_stmt, except force the retention of the BLOCK. */
tree
c_begin_omp_parallel (void)
{
tree block;
keep_next_level ();
block = c_begin_compound_stmt (true);
return block;
}
tree
c_finish_omp_parallel (tree clauses, tree block)
{
tree stmt;
block = c_end_compound_stmt (block, true);
stmt = make_node (OMP_PARALLEL);
TREE_TYPE (stmt) = void_type_node;
OMP_PARALLEL_CLAUSES (stmt) = clauses;
OMP_PARALLEL_BODY (stmt) = block;
return add_stmt (stmt);
}
/* For all elements of CLAUSES, validate them vs OpenMP constraints.
Remove any elements from the list that are invalid. */
tree
c_finish_omp_clauses (tree clauses)
{
bitmap_head generic_head, firstprivate_head, lastprivate_head;
tree c, t, *pc = &clauses;
const char *name;
bitmap_obstack_initialize (NULL);
bitmap_initialize (&generic_head, &bitmap_default_obstack);
bitmap_initialize (&firstprivate_head, &bitmap_default_obstack);
bitmap_initialize (&lastprivate_head, &bitmap_default_obstack);
for (pc = &clauses, c = clauses; c ; c = *pc)
{
bool remove = false;
bool need_complete = false;
bool need_implicitly_determined = false;
switch (OMP_CLAUSE_CODE (c))
{
case OMP_CLAUSE_SHARED:
name = "shared";
need_implicitly_determined = true;
goto check_dup_generic;
case OMP_CLAUSE_PRIVATE:
name = "private";
need_complete = true;
need_implicitly_determined = true;
goto check_dup_generic;
case OMP_CLAUSE_REDUCTION:
name = "reduction";
need_implicitly_determined = true;
t = OMP_CLAUSE_DECL (c);
if (AGGREGATE_TYPE_P (TREE_TYPE (t))
|| POINTER_TYPE_P (TREE_TYPE (t)))
{
error ("%qE has invalid type for %<reduction%>", t);
remove = true;
}
else if (FLOAT_TYPE_P (TREE_TYPE (t)))
{
enum tree_code r_code = OMP_CLAUSE_REDUCTION_CODE (c);
const char *r_name = NULL;
switch (r_code)
{
case PLUS_EXPR:
case MULT_EXPR:
case MINUS_EXPR:
break;
case BIT_AND_EXPR:
r_name = "&";
break;
case BIT_XOR_EXPR:
r_name = "^";
break;
case BIT_IOR_EXPR:
r_name = "|";
break;
case TRUTH_ANDIF_EXPR:
r_name = "&&";
break;
case TRUTH_ORIF_EXPR:
r_name = "||";
break;
default:
gcc_unreachable ();
}
if (r_name)
{
error ("%qE has invalid type for %<reduction(%s)%>",
t, r_name);
remove = true;
}
}
goto check_dup_generic;
case OMP_CLAUSE_COPYPRIVATE:
name = "copyprivate";
goto check_dup_generic;
case OMP_CLAUSE_COPYIN:
name = "copyin";
t = OMP_CLAUSE_DECL (c);
if (TREE_CODE (t) != VAR_DECL || !DECL_THREAD_LOCAL_P (t))
{
error ("%qE must be %<threadprivate%> for %<copyin%>", t);
remove = true;
}
goto check_dup_generic;
check_dup_generic:
t = OMP_CLAUSE_DECL (c);
if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
{
error ("%qE is not a variable in clause %qs", t, name);
remove = true;
}
else if (bitmap_bit_p (&generic_head, DECL_UID (t))
|| bitmap_bit_p (&firstprivate_head, DECL_UID (t))
|| bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
{
error ("%qE appears more than once in data clauses", t);
remove = true;
}
else
bitmap_set_bit (&generic_head, DECL_UID (t));
break;
case OMP_CLAUSE_FIRSTPRIVATE:
name = "firstprivate";
t = OMP_CLAUSE_DECL (c);
need_complete = true;
need_implicitly_determined = true;
if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
{
error ("%qE is not a variable in clause %<firstprivate%>", t);
remove = true;
}
else if (bitmap_bit_p (&generic_head, DECL_UID (t))
|| bitmap_bit_p (&firstprivate_head, DECL_UID (t)))
{
error ("%qE appears more than once in data clauses", t);
remove = true;
}
else
bitmap_set_bit (&firstprivate_head, DECL_UID (t));
break;
case OMP_CLAUSE_LASTPRIVATE:
name = "lastprivate";
t = OMP_CLAUSE_DECL (c);
need_complete = true;
need_implicitly_determined = true;
if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL)
{
error ("%qE is not a variable in clause %<lastprivate%>", t);
remove = true;
}
else if (bitmap_bit_p (&generic_head, DECL_UID (t))
|| bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
{
error ("%qE appears more than once in data clauses", t);
remove = true;
}
else
bitmap_set_bit (&lastprivate_head, DECL_UID (t));
break;
case OMP_CLAUSE_IF:
case OMP_CLAUSE_NUM_THREADS:
case OMP_CLAUSE_SCHEDULE:
case OMP_CLAUSE_NOWAIT:
case OMP_CLAUSE_ORDERED:
case OMP_CLAUSE_DEFAULT:
pc = &OMP_CLAUSE_CHAIN (c);
continue;
default:
gcc_unreachable ();
}
if (!remove)
{
t = OMP_CLAUSE_DECL (c);
if (need_complete)
{
t = require_complete_type (t);
if (t == error_mark_node)
remove = true;
}
if (need_implicitly_determined)
{
const char *share_name = NULL;
if (TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t))
share_name = "threadprivate";
else switch (c_omp_predetermined_sharing (t))
{
case OMP_CLAUSE_DEFAULT_UNSPECIFIED:
break;
case OMP_CLAUSE_DEFAULT_SHARED:
share_name = "shared";
break;
case OMP_CLAUSE_DEFAULT_PRIVATE:
share_name = "private";
break;
default:
gcc_unreachable ();
}
if (share_name)
{
error ("%qE is predetermined %qs for %qs",
t, share_name, name);
remove = true;
}
}
}
if (remove)
*pc = OMP_CLAUSE_CHAIN (c);
else
pc = &OMP_CLAUSE_CHAIN (c);
}
bitmap_obstack_release (NULL);
return clauses;
}
| bsd-3-clause |
appleseedhq/cortex | include/IECore/FromCoreConverter.h | 2945 | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECORE_FROMCORECONVERTER_H
#define IECORE_FROMCORECONVERTER_H
#include "IECore/Converter.h"
#include "IECore/Export.h"
#include "IECore/ObjectParameter.h"
namespace IECore
{
/// The FromCoreConverter class is a Converter derived class to be
/// used as a base for all classes able to perform some kind of
/// conversion from an IECore datatype to an external datatype.
class IECORE_API FromCoreConverter : public Converter
{
public :
IE_CORE_DECLARERUNTIMETYPED( FromCoreConverter, Converter );
/// The parameter holding the object to be converted.
ObjectParameterPtr srcParameter();
ConstObjectParameterPtr srcParameter() const;
protected :
FromCoreConverter( const std::string &description, TypeId supportedType );
FromCoreConverter( const std::string &description, const ObjectParameter::TypeIdSet &supportedTypes );
FromCoreConverter( const std::string &description, const TypeId *supportedTypes );
~FromCoreConverter() override;
private :
ObjectParameterPtr m_srcParameter;
};
IE_CORE_DECLAREPTR( FromCoreConverter );
} // namespace IECore
#endif // IECORE_FROMCORECONVERTER_H
| bsd-3-clause |
yannisgu/shouldly | src/Shouldly.Tests/Strings/DetailedDifference/CaseInsensitive/LongStrings/MultipleDiffs/DiffsCloseToEachOtherAreConsolidatedBorderConditionOne.cs | 3647 | using Shouldly.Tests.TestHelpers;
namespace Shouldly.Tests.Strings.DetailedDifference.CaseInsensitive.LongStrings.MultipleDiffs
{
// Just before the edge case for consolidation. 2 differences are exactly the required length apart to be consolidated into one diff
public class DiffsCloseToEachOtherAreConsolidatedBorderConditionOne: ShouldlyShouldTestScenario
{
protected override void ShouldPass()
{
"1A,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v"
.ShouldBe(
"1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v",
Case.Insensitive);
}
protected override void ShouldThrowAWobbly()
{
"1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v"
.ShouldBe(
"1a,1b.1c,1d,1e,1f,1g,1h,1j,1j,1k,1l,1m,1n,1o.1p,1q,1r,1s,1t,1u,1w",
Case.Insensitive);
}
protected override string ChuckedAWobblyErrorMessage
{
get
{
return @"""1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v""
should be
""1a,1b.1c,1d,1e,1f,1g,1h,1j,1j,1k,1l,1m,1n,1o.1p,1q,1r,1s,1t,1u,1w""
but was
""1a,1b,1c,1d,1e,1f,1g,1h,1i,1j,1k,1l,1m,1n,1o,1p,1q,1r,1s,1t,1u,1v""
difference
Case Insensitive Comparison
Difference | | |
| \|/ \|/
Index | ... 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ...
Expected Value | ... . 1 c , 1 d , 1 e , 1 f , 1 g , 1 h , 1 j ...
Actual Value | ... , 1 c , 1 d , 1 e , 1 f , 1 g , 1 h , 1 i ...
Expected Code | ... 46 49 99 44 49 100 44 49 101 44 49 102 44 49 103 44 49 104 44 49 106 ...
Actual Code | ... 44 49 99 44 49 100 44 49 101 44 49 102 44 49 103 44 49 104 44 49 105 ...
Difference | | |
| \|/ \|/
Index | ... 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
Expected Value | ... . 1 p , 1 q , 1 r , 1 s , 1 t , 1 u , 1 w
Actual Value | ... , 1 p , 1 q , 1 r , 1 s , 1 t , 1 u , 1 v
Expected Code | ... 46 49 112 44 49 113 44 49 114 44 49 115 44 49 116 44 49 117 44 49 119
Actual Code | ... 44 49 112 44 49 113 44 49 114 44 49 115 44 49 116 44 49 117 44 49 118 "
;
}
}
}
}
| bsd-3-clause |
serge-sans-paille/pythran | docs/papers/wpmvp14/experiments/run_xp_sum0.sh | 518 | rm *.so
export PATH=../../../../scripts:$PATH
export PYTHONPATH=../../../..
sed 's/vsum/sum/' sum0.py > ssum0.py
python -m timeit -s 'from ssum0 import sum0 as s; import numpy as np ; r = np.random.rand(1000000)' 's(r)'
rm -f ssum0.py
pythran -O2 sum0.py
python -m timeit -s 'from sum0 import sum0 as s; import numpy as np ; r = np.random.rand(1000000)' 's(r)'
pythran -O2 -DUSE_BOOST_SIMD -march=native sum0.py
python -m timeit -s 'from sum0 import sum0 as s; import numpy as np ; r = np.random.rand(1000000)' 's(r)'
| bsd-3-clause |
danakj/chromium | third_party/WebKit/LayoutTests/bluetooth/requestDevice/chooser/new-scan-device-added.html | 991 | <!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<script src="../../../resources/bluetooth/bluetooth-helpers.js"></script>
<script>
'use strict';
promise_test(() => {
testRunner.setBluetoothManualChooser(true);
let requestDevicePromise =
setBluetoothFakeAdapter('DeviceEventAdapter')
.then(() => requestDeviceWithKeyDown({
filters: [{services: ['glucose']}]}));
return getBluetoothManualChooserEvents(4).then(events => {
assert_equals(events[0], 'chooser-opened(file://)');
assert_equals(events[1], 'discovering');
let idsByName = new AddDeviceEventSet();
idsByName.assert_add_device_event(events[2]);
assert_true(idsByName.has('New Glucose Device'));
assert_equals(events[3], 'discovery-idle');
testRunner.sendBluetoothManualChooserEvent(
'selected', idsByName.get('New Glucose Device'));
return requestDevicePromise;
});
});
</script>
| bsd-3-clause |
mfroeling/DTITools | docs/htmldoc/standard/javascript/search.js | 723 | function setSearchTextField(paramname, field) {
var passed = location.search.substring(1);
var query = getParm(passed,paramname);
var query = getParm(passed,paramname);
query = query.replace(/\+/g," ");
var loc = document.location;
if(/.*search.html/.test(loc)) {
document.title = decodeURIComponent(query) + ' - Wolfram Search';
}
field.value = decodeURIComponent(query);
}
function getParm(string,parm) {
// returns value of parm from string
var startPos = string.indexOf(parm + "=");
if (startPos > -1) {
startPos = startPos + parm.length + 1;
var endPos = string.indexOf("&",startPos);
if (endPos == -1)
endPos = string.length;
return string.substring(startPos,endPos);
}
return '';
}
| bsd-3-clause |
haskell-streaming/streaming | benchmarks/old/Stream/Folding/ByteString.hs | 7155 | {-# LANGUAGE LambdaCase, RankNTypes, ScopedTypeVariables #-}
module Stream.Folding.ByteString where
import Stream.Types
import Stream.Folding.Prelude hiding (fromHandle)
import Control.Monad hiding (filterM, mapM)
import Data.Functor.Identity
import Control.Monad.Trans
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.ByteString.Lazy.Internal (foldrChunks, defaultChunkSize)
import Data.ByteString (ByteString)
import qualified System.IO as IO
import Prelude hiding (map, filter, drop, take, sum
, iterate, repeat, replicate, splitAt
, takeWhile, enumFrom, enumFromTo)
import Foreign.C.Error (Errno(Errno), ePIPE)
import qualified GHC.IO.Exception as G
import Control.Exception (throwIO, try)
import Data.Word
fromLazy bs = Folding (\construct wrap done ->
foldrChunks (kurry construct) (done ()) bs)
stdinLn :: Folding (Of ByteString) IO ()
stdinLn = fromHandleLn IO.stdin
{-# INLINABLE stdinLn #-}
fromHandleLn :: IO.Handle -> Folding (Of ByteString) IO ()
fromHandleLn h = Folding $ \construct wrap done ->
wrap $ let go = do eof <- IO.hIsEOF h
if eof then return (done ())
else do bs <- B.hGetLine h
return (construct (bs :> wrap go))
in go
{-# INLINABLE fromHandleLn #-}
stdin :: Folding (Of ByteString) IO ()
stdin = fromHandle IO.stdin
fromHandle :: IO.Handle -> Folding (Of ByteString) IO ()
fromHandle = hGetSome defaultChunkSize
{-# INLINABLE fromHandle #-}
hGetSome :: Int -> IO.Handle -> Folding (Of ByteString) IO ()
hGetSome size h = Folding $ \construct wrap done ->
let go = do bs <- B.hGetSome h size
if B.null bs then return (done ())
else liftM (construct . (bs :>)) go
in wrap go
{-# INLINABLE hGetSome #-}
hGet :: Int -> IO.Handle -> Folding (Of ByteString) IO ()
hGet size h = Folding $ \construct wrap done ->
let go = do bs <- B.hGet h size
if B.null bs then return (done ())
else liftM (construct . (bs :>)) go
in wrap go
{-# INLINABLE hGet #-}
stdout :: MonadIO m => Folding (Of ByteString) m () -> m ()
stdout (Folding phi) =
phi (\(bs :> rest) ->
do x <- liftIO (try (B.putStr bs))
case x of
Left (G.IOError { G.ioe_type = G.ResourceVanished
, G.ioe_errno = Just ioe })
| Errno ioe == ePIPE
-> return ()
Left e -> liftIO (throwIO e)
Right () -> rest)
join
(\_ -> return ())
{-# INLINABLE stdout #-}
toHandle :: MonadIO m => IO.Handle -> Folding (Of ByteString) m () -> m ()
toHandle h (Folding phi) =
phi (\(bs :> rest) -> liftIO (B.hPut h bs) >> rest)
join
(\_ -> return ())
{-# INLINE toHandle #-}
-- span
-- :: Monad m
-- => (Word8 -> Bool)
-- -> Lens' (Producer ByteString m x)
-- (Producer ByteString m (Producer ByteString m x))
-- span_ :: Monad m
-- => Folding_ (Of ByteString) m r
-- -> (Word8 -> Bool)
-- -- span_ :: Folding_ (Of ByteString) m r
-- -- -> (Word8 -> Bool)
-- -> (Of ByteString r' -> r')
-- -> (m r' -> r')
-- -> (Folding (Of ByteString) m r -> r')
-- -> r'
--
-- span_ :: Monad m
-- => Folding (Of ByteString) m r
-- -> (Word8 -> Bool) -> Folding (Of ByteString) m (Folding (Of ByteString) m r)
-- ------------------------
-- span_ (Folding phi) p = Folding $ \construct wrap done ->
-- getFolding (phi
-- (\(bs :> rest) -> undefined)
-- (\mf -> undefined)
-- (\r c w d -> getFolding r c w d))
-- construct wrap done
-- ------------------------
-- (\(bs :> Folding rest) -> Folding $ \c w d ->
-- let (prefix, suffix) = B.span p bs
-- in if B.null suffix
-- then getFolding (rest c w d )
-- else c (prefix :> d rest)
-- (\mpsi -> Folding $ \c w d ->
-- w $ mpsi >>= \(Folding psi) -> return (psi c w d))
-- (\r -> Folding $ \c w d -> getFolding (d r))
--
-- Folding $ \c w d -> wrap $ mpsi >>= \(Folding psi) -> return (psi c w d)
-- where
-- go p = do
-- x <- lift (next p)
-- case x of
-- Left r -> return (return r)
-- Right (bs, p') -> do
-- let (prefix, suffix) = BS.span predicate bs
-- if (BS.null suffix)
-- then do
-- yield bs
-- go p'
-- else do
-- yield prefix
-- return (yield suffix >> p')
-- # INLINABLE span #-}
-- break predicate = span (not . predicate)
--
-- nl :: Word8
-- nl = fromIntegral (ord '\n')
--
-- _lines
-- :: Monad m => Producer ByteString m x -> FreeT (Producer ByteString m) m x
-- _lines p0 = PG.FreeT (go0 p0)
-- where
-- go0 p = do
-- x <- next p
-- case x of
-- Left r -> return (PG.Pure r)
-- Right (bs, p') ->
-- if (BS.null bs)
-- then go0 p'
-- else return $ PG.Free $ go1 (yield bs >> p')
-- go1 p = do
-- p' <- p^.line
-- return $ PG.FreeT $ do
-- x <- nextByte p'
-- case x of
-- Left r -> return (PG.Pure r)
-- Right (_, p'') -> go0 p''
-- {-# INLINABLE _lines #-}
--
-- _unlines
-- :: Monad m => FreeT (Producer ByteString m) m x -> Producer ByteString m x
-- _unlines = concats . PG.maps addNewline
-- where
-- addNewline p = p <* yield (BS.singleton nl)
-- {-# INLINABLE _unlines #
--
--
splitAt :: (Monad m)
=> Int
-> Folding (Of ByteString) m r
-> Folding (Of ByteString) m (Folding (Of ByteString) m r)
splitAt n0 (Folding phi) =
phi
(\(bs :> nfold) n ->
let len = fromIntegral (B.length bs)
rest = joinFold (nfold (n-len))
in if n > 0
then if n > len
then Folding $ \construct wrap done -> construct $
bs :> getFolding (nfold (n-len)) construct wrap done
else let (prefix, suffix) = B.splitAt (fromIntegral n) bs
in Folding $ \construct wrap done -> construct $
if B.null suffix
then prefix :> done rest
else prefix :> done (cons suffix rest)
else Folding $ \construct wrap done -> done $
bs `cons` rest
)
(\m n -> Folding $ \construct wrap done -> wrap $
liftM (\f -> getFolding (f n) construct wrap done) m
)
(\r n -> Folding $ \construct wrap done -> done $
Folding $ \c w d -> d r
)
n0
| bsd-3-clause |
fxtentacle/Telephone | Classes/AKKeychain.h | 2278 | //
// AKKeychain.h
// Telephone
//
// Copyright (c) 2008-2012 Alexei Kuznetsov. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT HOLDER
// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import <Foundation/Foundation.h>
// A Keychain Services wrapper.
@interface AKKeychain : NSObject
// Returns password for the first Keychain item with a specified service name and account name.
+ (NSString *)passwordForServiceName:(NSString *)serviceName accountName:(NSString *)accountName;
// Adds an item to the Keychain with a specified service name, account name, and password. If the same item already
// exists, its password will be replaced with the new one.
+ (BOOL)addItemWithServiceName:(NSString *)serviceName
accountName:(NSString *)accountName
password:(NSString *)password;
@end
| bsd-3-clause |
chromium/chromium | ash/in_session_auth/auth_dialog_contents_view.h | 5874 | // Copyright 2020 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 ASH_IN_SESSION_AUTH_AUTH_DIALOG_CONTENTS_VIEW_H_
#define ASH_IN_SESSION_AUTH_AUTH_DIALOG_CONTENTS_VIEW_H_
#include <string>
#include "ash/login/ui/login_palette.h"
#include "ash/public/cpp/login_types.h"
#include "ui/views/view.h"
namespace views {
class BoxLayout;
class Label;
class LabelButton;
class MdTextButton;
} // namespace views
namespace ash {
class AnimatedRoundedImageView;
class LoginPasswordView;
class LoginPinView;
class LoginPinInputView;
// Contains the debug views that allows the developer to interact with the
// AuthDialogController.
class AuthDialogContentsView : public views::View {
public:
// Flags which describe the set of currently visible auth methods.
enum AuthMethods {
kAuthNone = 0, // No auth methods.
kAuthPassword = 1 << 0, // Display password.
kAuthPin = 1 << 1, // Display PIN keyboard.
kAuthFingerprint = 1 << 2, // Use fingerprint to unlock.
};
// Extra control parameters to be passed when setting the auth methods.
struct AuthMethodsMetadata {
// User's pin length to use for autosubmit.
size_t autosubmit_pin_length = 0;
};
AuthDialogContentsView(uint32_t auth_methods,
const std::string& origin_name,
const AuthMethodsMetadata& auth_metadata,
const UserAvatar& avatar);
AuthDialogContentsView(const AuthDialogContentsView&) = delete;
AuthDialogContentsView& operator=(const AuthDialogContentsView&) = delete;
~AuthDialogContentsView() override;
// views::Views:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void RequestFocus() override;
uint32_t auth_methods() const { return auth_methods_; }
private:
class TitleLabel;
class FingerprintView;
// views::View:
void AddedToWidget() override;
// Add a view for user avatar.
void AddAvatarView(const UserAvatar& avatar);
// Add a view for dialog title.
void AddTitleView();
// Add a view that shows which website/app we are authenticating for.
void AddOriginNameView();
// Add a view for entering PIN (if autosubmit is off).
void AddPinTextInputView();
// Add a view for entering password.
void AddPasswordView();
// Add a PIN pad view.
void AddPinPadView();
// Add a PIN input view that automatically submits PIN.
void AddPinDigitInputView();
// Add a vertical spacing view.
void AddVerticalSpacing(int height);
// Add a view for action buttons.
void AddActionButtonsView();
// Called when the user taps a digit on the PIN pad.
void OnInsertDigitFromPinPad(int digit);
// Called when the user taps backspace on the PIN pad.
void OnBackspaceFromPinPad();
// Called when either:
// 1. the user inserts or deletes a character in
// |pin_text_input_view_| or |pin_digit_input_view_| without using the PIN
// pad, or
// 2. the user inserts or deletes a character in |password_view_|, or
// 3. contents of |pin_text_input_view_|, |password_view_|, or
// |pin_digit_input_view_| are cleared by a Reset() call.
void OnInputTextChanged(bool is_empty);
// Called when the user submits password or PIN. If authenticated_by_pin is
// false, the user authenticated by password.
void OnAuthSubmit(bool authenticated_by_pin, const std::u16string& password);
// Called when password or PIN authentication of the user completes. If
// authenticated_by_pin is false, the user authenticated by password.
void OnPasswordOrPinAuthComplete(bool authenticated_by_pin,
absl::optional<bool> success);
// Called when fingerprint authentication completes.
void OnFingerprintAuthComplete(bool success,
FingerprintState fingerprint_state);
// Called when the cancel button is pressed.
void OnCancelButtonPressed(const ui::Event& event);
// Called when the "Need help?" button is pressed.
void OnNeedHelpButtonPressed(const ui::Event& event);
// Debug container which holds the entire debug UI.
views::View* container_ = nullptr;
// Layout for |container_|.
views::BoxLayout* main_layout_ = nullptr;
// User avatar to indicate this is an OS dialog.
AnimatedRoundedImageView* avatar_view_ = nullptr;
// Title of the auth dialog, also used to show PIN auth error message..
TitleLabel* title_ = nullptr;
// Prompt message to the user.
views::Label* origin_name_view_ = nullptr;
// Whether PIN can be auto submitted.
bool pin_autosubmit_on_ = false;
// Number of PIN attempts so far.
int pin_attempts_ = 0;
// Text input field for PIN if PIN cannot be auto submitted.
LoginPasswordView* pin_text_input_view_ = nullptr;
// PIN input view that's shown if PIN can be auto submitted.
LoginPinInputView* pin_digit_input_view_ = nullptr;
// Text input field for password.
LoginPasswordView* password_view_ = nullptr;
// PIN pad view.
LoginPinView* pin_pad_view_ = nullptr;
FingerprintView* fingerprint_view_ = nullptr;
// A button to cancel authentication and close the dialog.
views::MdTextButton* cancel_button_ = nullptr;
// A button to show a help center article.
views::LabelButton* help_button_ = nullptr;
// Flags of auth methods that should be visible.
uint32_t auth_methods_ = 0u;
const std::string origin_name_;
// Extra parameters to control the UI.
AuthMethodsMetadata auth_metadata_;
LoginPalette palette_ = CreateInSessionAuthPalette();
// Container which holds action buttons.
views::View* action_view_container_ = nullptr;
base::WeakPtrFactory<AuthDialogContentsView> weak_factory_{this};
};
} // namespace ash
#endif // ASH_IN_SESSION_AUTH_AUTH_DIALOG_CONTENTS_VIEW_H_
| bsd-3-clause |
chromium/chromium | components/segmentation_platform/internal/ukm_data_manager.h | 2862 | // Copyright 2022 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 COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_UKM_DATA_MANAGER_H_
#define COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_UKM_DATA_MANAGER_H_
namespace base {
class FilePath;
}
namespace ukm {
class UkmRecorderImpl;
}
namespace segmentation_platform {
class UkmDatabase;
class UrlSignalHandler;
class UkmConfig;
// Manages ownership and lifetime of all UKM related classes, like database and
// observer. There is only one manager per browser process. Created before
// profile initialization and destroyed after all profiles are destroyed. The
// database, observer and signal handler can have different lifetimes, see
// comments below.
class UkmDataManager {
public:
UkmDataManager() = default;
virtual ~UkmDataManager() = default;
UkmDataManager(UkmDataManager&) = delete;
UkmDataManager& operator=(UkmDataManager&) = delete;
// Initializes UKM database.
virtual void Initialize(const base::FilePath& database_path) = 0;
// Returns true when UKM engine is usable. If false, then UKM based engine is
// disabled and this class is a no-op. UkmObserver, UrlSignalHandler and
// UkmDatabase are not created and are unusable when this method returns
// false.
virtual bool IsUkmEngineEnabled() = 0;
// Must be called when UKM service is available to start observing metrics.
virtual void NotifyCanObserveUkm(ukm::UkmRecorderImpl* ukm_recorder) = 0;
// Can be called at any time, irrespective of UKM observer's lifetime. If
// NotifyCanObserveUkm() was already called, then starts observing UKM with
// the given config. Else, starts when NotifyCanObserveUkm() is called. If
// called after StopObservingUkm(), does nothing.
virtual void StartObservingUkm(const UkmConfig& config) = 0;
// Pauses or resumes observation of UKM, can be called any time, irrespective
// of UKM observer's lifetime, similar to StartObservingUkm().
virtual void PauseOrResumeObservation(bool pause) = 0;
// Must be called before UKM service is destroyed, to remove observers.
virtual void StopObservingUkm() = 0;
// Get URL signal handler. The signal handler is safe to use as long as data
// manager is alive, so until after all profiles are destroyed.
virtual UrlSignalHandler* GetOrCreateUrlHandler() = 0;
// Get UKM database. The database is safe to use as long as data manager is
// alive, so until after all profiles are destroyed.
virtual UkmDatabase* GetUkmDatabase() = 0;
// Keep track of all the segmentation services that hold reference to this
// object.
virtual void AddRef() = 0;
virtual void RemoveRef() = 0;
};
} // namespace segmentation_platform
#endif // COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_UKM_DATA_MANAGER_H_
| bsd-3-clause |
anusornc/vitess | test/framework.py | 2552 | # Copyright 2012, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import os
import shlex
from subprocess import Popen, PIPE
import time
import unittest
import utils
class TestCase(unittest.TestCase):
@classmethod
def setenv(cls, env):
cls.env = env
def assertContains(self, b, a):
self.assertTrue(a in b, "%r not found in %r" % (a, b))
class MultiDict(dict):
def __getattr__(self, name):
v = self[name]
if type(v)==dict:
v=MultiDict(v)
return v
def mget(self, mkey, default=None):
keys = mkey.split(".")
try:
v = self
for key in keys:
v = v[key]
except KeyError:
v = default
if type(v)==dict:
v = MultiDict(v)
return v
class Tailer(object):
def __init__(self, filepath, flush=None, sleep=0, timeout=10.0):
self.filepath = filepath
self.flush = flush
self.sleep = sleep
self.timeout = timeout
self.f = None
self.reset()
def reset(self):
"""Call reset when you want to start using the tailer."""
if self.flush:
self.flush()
else:
time.sleep(self.sleep)
# Re-open the file if open.
if self.f:
self.f.close()
self.f = None
# Wait for file to exist.
timeout = self.timeout
while not os.path.exists(self.filepath):
timeout = utils.wait_step('file exists: ' + self.filepath, timeout)
self.f = open(self.filepath)
self.f.seek(0, os.SEEK_END)
self.pos = self.f.tell()
def read(self):
"""Returns a string which may contain multiple lines."""
if self.flush:
self.flush()
else:
time.sleep(self.sleep)
self.f.seek(0, os.SEEK_END)
newpos = self.f.tell()
if newpos < self.pos:
return ""
self.f.seek(self.pos, os.SEEK_SET)
size = newpos-self.pos
self.pos = newpos
return self.f.read(size)
def readLines(self):
"""Returns a list of read lines."""
return self.read().splitlines()
# FIXME: Hijacked from go/vt/tabletserver/test.py
# Reuse when things come together
def execute(cmd, trap_output=False, verbose=False, **kargs):
args = shlex.split(cmd)
if trap_output:
kargs['stdout'] = PIPE
kargs['stderr'] = PIPE
if verbose:
print "Execute:", cmd, ', '.join('%s=%s' % x for x in kargs.iteritems())
proc = Popen(args, **kargs)
proc.args = args
stdout, stderr = proc.communicate()
if proc.returncode:
raise Exception('FAIL: %s %s %s' % (args, stdout, stderr))
return stdout, stderr
| bsd-3-clause |
pdalpra/sbt | main/src/main/scala/sbt/SessionSettings.scala | 13670 | /* sbt -- Simple Build Tool
* Copyright 2011 Mark Harrah
*/
package sbt
import java.io.File
import java.net.URI
import Def.{ ScopedKey, Setting }
import Types.Endo
import compiler.Eval
import SessionSettings._
import sbt.internals.parser.SbtRefactorings
/**
* Represents (potentially) transient settings added into a build via commands/user.
*
* @param currentBuild
* The current sbt build with which we scope new settings
* @param currentProject
* The current project with which we scope new settings.
* @param original
* The original list of settings for this build.
* @param append
* Settings which have been defined and appended that may ALSO be saved to disk.
* @param rawAppend
* Settings which have been defined and appended which CANNOT be saved to disk
* @param currentEval
* A compiler we can use to compile new setting strings.
*/
final case class SessionSettings(currentBuild: URI, currentProject: Map[URI, String], original: Seq[Setting[_]], append: SessionMap, rawAppend: Seq[Setting[_]], currentEval: () => Eval) {
assert(currentProject contains currentBuild, "Current build (" + currentBuild + ") not associated with a current project.")
/**
* Modifiy the current state.
*
* @param build The buid with which we scope new settings.
* @param project The project reference with which we scope new settings.
* @param eval The mechanism to compile new settings.
* @return A new SessionSettings object
*/
def setCurrent(build: URI, project: String, eval: () => Eval): SessionSettings = copy(currentBuild = build, currentProject = currentProject.updated(build, project), currentEval = eval)
/**
* @return The current ProjectRef with which we scope settings.
*/
def current: ProjectRef = ProjectRef(currentBuild, currentProject(currentBuild))
/**
* Appends a set of settings which can be persisted to disk
* @param s A sequence of SessionSetting objects, which contain a Setting[_] and a string.
* @return A new SessionSettings which contains this new sequence.
*/
def appendSettings(s: Seq[SessionSetting]): SessionSettings = copy(append = modify(append, _ ++ s))
/**
* Appends a set of raw Setting[_] objects to the current session.
* @param ss The raw settings to include
* @return A new SessionSettings with the appeneded settings.
*/
def appendRaw(ss: Seq[Setting[_]]): SessionSettings = copy(rawAppend = rawAppend ++ ss)
/**
* @return A combined list of all Setting[_] objects for the current session, in priority order.
*/
def mergeSettings: Seq[Setting[_]] = original ++ merge(append) ++ rawAppend
/**
* @return A new SessionSettings object where additional transient settings are removed.
*/
def clearExtraSettings: SessionSettings = copy(append = Map.empty, rawAppend = Nil)
private[this] def merge(map: SessionMap): Seq[Setting[_]] = map.values.toSeq.flatten[SessionSetting].map(_._1)
private[this] def modify(map: SessionMap, onSeq: Endo[Seq[SessionSetting]]): SessionMap = {
val cur = current
map.updated(cur, onSeq(map.getOrElse(cur, Nil)))
}
}
object SessionSettings {
/** A session setting is simply a tuple of a Setting[_] and the strings which define it. */
type SessionSetting = (Setting[_], Seq[String])
type SessionMap = Map[ProjectRef, Seq[SessionSetting]]
type SbtConfigFile = (File, Seq[String])
/**
* This will re-evaluate all Setting[_]'s on this session against the current build state and
* return the new build state.
*/
def reapply(session: SessionSettings, s: State): State =
BuiltinCommands.reapply(session, Project.structure(s), s)
/**
* This will clear any user-added session settings for a given build state and return the new build state.
*
* Note: Does not clear `rawAppend` settings
*/
def clearSettings(s: State): State =
withSettings(s)(session => reapply(session.copy(append = session.append - session.current), s))
/** This will clear ALL transient session settings in a given build state, returning the new build state. */
def clearAllSettings(s: State): State =
withSettings(s)(session => reapply(session.clearExtraSettings, s))
/**
* A convenience method to alter the current build state using the current SessionSettings.
*
* @param s The current build state
* @param f A function which takes the current SessionSettings and returns the new build state.
* @return The new build state
*/
def withSettings(s: State)(f: SessionSettings => State): State = {
val extracted = Project extract s
import extracted._
if (session.append.isEmpty) {
s.log.info("No session settings defined.")
s
} else
f(session)
}
/** Adds `s` to a strings when needed. Maybe one day we'll care about non-english languages. */
def pluralize(size: Int, of: String) = size.toString + (if (size == 1) of else (of + "s"))
/** Checks to see if any session settings are being discarded and issues a warning. */
def checkSession(newSession: SessionSettings, oldState: State) {
val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2)
if (newSession.append.isEmpty && oldSettings.nonEmpty)
oldState.log.warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.")
}
@deprecated("This method will no longer be public", "0.13.7")
def removeRanges[T](in: Seq[T], ranges: Seq[(Int, Int)]): Seq[T] = {
val asSet = (Set.empty[Int] /: ranges) { case (s, (hi, lo)) => s ++ (hi to lo) }
in.zipWithIndex.flatMap { case (t, index) => if (asSet(index + 1)) Nil else t :: Nil }
}
/**
* Removes settings from the current session, by range.
* @param s The current build state.
* @param ranges A set of Low->High tuples for which settings to remove.
* @return The new build state with settings removed.
*/
def removeSettings(s: State, ranges: Seq[(Int, Int)]): State =
withSettings(s) { session =>
val current = session.current
val newAppend = session.append.updated(current, removeRanges(session.append.getOrElse(current, Nil), ranges))
reapply(session.copy(append = newAppend), s)
}
/** Saves *all* session settings to disk for all projects. */
def saveAllSettings(s: State): State = saveSomeSettings(s)(_ => true)
/** Saves the session settings to disk for the current project. */
def saveSettings(s: State): State = {
val current = Project.session(s).current
saveSomeSettings(s)(_ == current)
}
/**
* Saves session settings to disk if they match the filter.
* @param s The build state
* @param include A filter function to determine which project's settings to persist.
* @return The new build state.
*/
def saveSomeSettings(s: State)(include: ProjectRef => Boolean): State =
withSettings(s) { session =>
val newSettings =
for ((ref, settings) <- session.append if settings.nonEmpty && include(ref)) yield {
val (news, olds) = writeSettings(ref, settings.toList, session.original, Project.structure(s))
(ref -> news, olds)
}
val (newAppend, newOriginal) = newSettings.unzip
val newSession = session.copy(append = newAppend.toMap, original = newOriginal.flatten.toSeq)
reapply(newSession.copy(original = newSession.mergeSettings, append = Map.empty), s)
}
@deprecated("This method will no longer be public", "0.13.7")
def writeSettings(pref: ProjectRef, settings: List[SessionSetting], original: Seq[Setting[_]], structure: BuildStructure): (Seq[SessionSetting], Seq[Setting[_]]) = {
val project = Project.getProject(pref, structure).getOrElse(sys.error("Invalid project reference " + pref))
val writeTo: File = BuildPaths.configurationSources(project.base).headOption.getOrElse(new File(project.base, "build.sbt"))
writeTo.createNewFile()
val path = writeTo.getAbsolutePath
val (inFile, other, _) = ((List[Setting[_]](), List[Setting[_]](), Set.empty[ScopedKey[_]]) /: original.reverse) {
case ((in, oth, keys), s) =>
s.pos match {
case RangePosition(`path`, _) if !keys.contains(s.key) => (s :: in, oth, keys + s.key)
case _ => (in, s :: oth, keys)
}
}
val (_, oldShifted, replace) = ((0, List[Setting[_]](), Seq[SessionSetting]()) /: inFile) {
case ((offs, olds, repl), s) =>
val RangePosition(_, r @ LineRange(start, end)) = s.pos
settings find (_._1.key == s.key) match {
case Some(ss @ (ns, newLines)) if !ns.init.dependencies.contains(ns.key) =>
val shifted = ns withPos RangePosition(path, LineRange(start - offs, start - offs + newLines.size))
(offs + end - start - newLines.size, shifted :: olds, ss +: repl)
case _ =>
val shifted = s withPos RangePosition(path, r shift -offs)
(offs, shifted :: olds, repl)
}
}
val newSettings = settings diff replace
val oldContent = IO.readLines(writeTo)
val (_, exist) = SbtRefactorings.applySessionSettings((writeTo, oldContent), replace)
val adjusted = if (newSettings.nonEmpty && needsTrailingBlank(exist)) exist :+ "" else exist
val lines = adjusted ++ newSettings.flatMap(x => x._2 :+ "")
IO.writeLines(writeTo, lines)
val (newWithPos, _) = ((List[SessionSetting](), adjusted.size + 1) /: newSettings) {
case ((acc, line), (s, newLines)) =>
val endLine = line + newLines.size
((s withPos RangePosition(path, LineRange(line, endLine)), newLines) :: acc, endLine + 1)
}
(newWithPos.reverse, other ++ oldShifted)
}
@deprecated("This method will no longer be public", "0.13.7")
def needsTrailingBlank(lines: Seq[String]) = lines.nonEmpty && !lines.takeRight(1).exists(_.trim.isEmpty)
/** Prints all the user-defined SessionSettings (not raw) to System.out. */
def printAllSettings(s: State): State =
withSettings(s) { session =>
for ((ref, settings) <- session.append if settings.nonEmpty) {
println("In " + Reference.display(ref))
printSettings(settings)
}
s
}
/** Prints all the defined session settings for the current project in the given build state. */
def printSettings(s: State): State =
withSettings(s) { session =>
printSettings(session.append.getOrElse(session.current, Nil))
s
}
/** Prints all the passed in session settings */
def printSettings(settings: Seq[SessionSetting]): Unit =
for (((_, stringRep), index) <- settings.zipWithIndex)
println(" " + (index + 1) + ". " + stringRep.mkString("\n"))
def Help = """session <command>
Manipulates session settings, which are temporary settings that do not persist past the current sbt execution (that is, the current session).
Valid commands are:
clear, clear-all
Removes temporary settings added using 'set' and re-evaluates all settings.
For 'clear', only the settings defined for the current project are cleared.
For 'clear-all', all settings in all projects are cleared.
list, list-all
Prints a numbered list of session settings defined.
The numbers may be used to remove individual settings or ranges of settings using 'remove'.
For 'list', only the settings for the current project are printed.
For 'list-all', all settings in all projets are printed.
remove <range-spec>
<range-spec> is a comma-separated list of individual numbers or ranges of numbers.
For example, 'remove 1,3,5-7'.
The temporary settings at the given indices for the current project are removed and all settings are re-evaluated.
Use the 'list' command to see a numbered list of settings for the current project.
save, save-all
Makes the session settings permanent by writing them to a '.sbt' configuration file.
For 'save', only the current project's settings are saved (the settings for other projects are left alone).
For 'save-all', the session settings are saved for all projects.
The session settings defined for a project are appended to the first '.sbt' configuration file in that project.
If no '.sbt' configuration file exists, the settings are written to 'build.sbt' in the project's base directory."""
/** AST for the syntax of the session command. Each subclass is an action that can be performed. */
sealed trait SessionCommand
final class Print(val all: Boolean) extends SessionCommand
final class Clear(val all: Boolean) extends SessionCommand
final class Save(val all: Boolean) extends SessionCommand
final class Remove(val ranges: Seq[(Int, Int)]) extends SessionCommand
import complete._
import DefaultParsers._
/** Parser for the session command. */
lazy val parser =
token(Space) ~>
(token("list-all" ^^^ new Print(true)) | token("list" ^^^ new Print(false)) | token("clear" ^^^ new Clear(false)) |
token("save-all" ^^^ new Save(true)) | token("save" ^^^ new Save(false)) | token("clear-all" ^^^ new Clear(true)) |
remove)
lazy val remove = token("remove") ~> token(Space) ~> natSelect.map(ranges => new Remove(ranges))
def natSelect = rep1sep(token(range, "<range>"), ',')
def range: Parser[(Int, Int)] = (NatBasic ~ ('-' ~> NatBasic).?).map { case lo ~ hi => (lo, hi getOrElse lo) }
/** The raw implementation of the session command. */
def command(s: State) = Command.applyEffect(parser) {
case p: Print => if (p.all) printAllSettings(s) else printSettings(s)
case v: Save => if (v.all) saveAllSettings(s) else saveSettings(s)
case c: Clear => if (c.all) clearAllSettings(s) else clearSettings(s)
case r: Remove => removeSettings(s, r.ranges)
}
}
| bsd-3-clause |
hadess/spksrc | toolchains/syno-ppc824x/Makefile | 376 | TC_NAME = syno-ppc824x
TC_DIST_NAME = gcc334_glibc233_ppc824x-GPL.tgz
TC_EXT = tgz
TC_DIST_SITE = http://sourceforge.net/projects/dsgpl/files/DSM%204.2%20Tool%20Chains/PowerPC%20824x%20Linux%202.6.24
TC_BASE_DIR = powerpc-linux
TC_PREFIX = powerpc-linux
TC_TARGET = powerpc-unknown-linux
TC_CFLAGS =
TC_CPPFLAGS =
TC_CXXFLAGS =
TC_LDFLAGS =
include ../../mk/spksrc.tc.mk
| bsd-3-clause |
igor-m/retrobsd-active | src/cmd/wc.c | 2235 | /*
* wc line and word count
*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#include <stdio.h>
#include <stdlib.h>
long linect, wordct, charct, pagect;
long tlinect, twordct, tcharct, tpagect;
char *wd = "lwc";
main(argc, argv)
char **argv;
{
int i, token;
register FILE *fp;
register int c;
char *p;
while (argc > 1 && *argv[1] == '-') {
switch (argv[1][1]) {
case 'l': case 'w': case 'c':
wd = argv[1]+1;
break;
default:
usage:
fprintf(stderr, "Usage: wc [-lwc] [files]\n");
exit(1);
}
argc--;
argv++;
}
i = 1;
fp = stdin;
do {
if(argc>1 && (fp=fopen(argv[i], "r")) == NULL) {
perror(argv[i]);
continue;
}
linect = 0;
wordct = 0;
charct = 0;
token = 0;
for(;;) {
c = getc(fp);
if (c == EOF)
break;
charct++;
if(' '<c&&c<0177) {
if(!token) {
wordct++;
token++;
}
continue;
}
if(c=='\n') {
linect++;
}
else if(c!=' '&&c!='\t')
continue;
token = 0;
}
/* print lines, words, chars */
wcp(wd, charct, wordct, linect);
if(argc>1) {
printf(" %s\n", argv[i]);
} else
printf("\n");
fclose(fp);
tlinect += linect;
twordct += wordct;
tcharct += charct;
} while(++i<argc);
if(argc > 2) {
wcp(wd, tcharct, twordct, tlinect);
printf(" total\n");
}
exit(0);
}
wcp(wd, charct, wordct, linect)
register char *wd;
long charct; long wordct; long linect;
{
while (*wd) switch (*wd++) {
case 'l':
ipr(linect);
break;
case 'w':
ipr(wordct);
break;
case 'c':
ipr(charct);
break;
}
}
ipr(num)
long num;
{
printf(" %7ld", num);
}
| bsd-3-clause |
tobspr/panda3d | pandatool/src/lwo/lwoSurfaceBlockCoordSys.h | 1325 | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file lwoSurfaceBlockCoordSys.h
* @author drose
* @date 2001-04-24
*/
#ifndef LWOSURFACEBLOCKCOORDSYS_H
#define LWOSURFACEBLOCKCOORDSYS_H
#include "pandatoolbase.h"
#include "lwoChunk.h"
/**
* Specifies whether texture coordinates are computed based on the vertices'
* world coordinates or local coordinates.
*/
class LwoSurfaceBlockCoordSys : public LwoChunk {
public:
enum Type {
T_object = 0,
T_world = 1
};
Type _type;
public:
virtual bool read_iff(IffInputFile *in, size_t stop_at);
virtual void write(ostream &out, int indent_level = 0) const;
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
LwoChunk::init_type();
register_type(_type_handle, "LwoSurfaceBlockCoordSys",
LwoChunk::get_class_type());
}
private:
static TypeHandle _type_handle;
};
#endif
| bsd-3-clause |
MKV21/glimpse_client | src/console/consoletools_win.cpp | 1142 | #include "consoletools.h"
#include "log/logger.h"
#include <QTextStream>
#include <Windows.h>
LOGGER(ConsoleTools);
class ConsoleTools::Private
{
public:
Private()
{
hConsole = ::GetStdHandle(STD_INPUT_HANDLE);
if (hConsole == INVALID_HANDLE_VALUE)
{
LOG_ERROR("Unable to get console handle");
}
}
HANDLE hConsole;
};
ConsoleTools::ConsoleTools()
: d(new Private)
{
}
ConsoleTools::~ConsoleTools()
{
enableEcho();
delete d;
}
bool ConsoleTools::enableEcho()
{
DWORD value;
::GetConsoleMode(d->hConsole, &value);
value |= ENABLE_ECHO_INPUT;
::SetConsoleMode(d->hConsole, value);
return true;
}
bool ConsoleTools::disableEcho()
{
DWORD value;
::GetConsoleMode(d->hConsole, &value);
value &= ~ENABLE_ECHO_INPUT;
::SetConsoleMode(d->hConsole, value);
return true;
}
QString ConsoleTools::readLine()
{
QTextStream stream(stdin);
return stream.readLine();
}
QString ConsoleTools::readPassword()
{
disableEcho();
QTextStream stream(stdin);
QString pw = stream.readLine();
enableEcho();
return pw;
}
| bsd-3-clause |
chromium/chromium | extensions/common/permissions/api_permission_set.cc | 11420 | // Copyright 2013 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.
#include "extensions/common/permissions/api_permission_set.h"
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/ranges/algorithm.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/permissions/permissions_info.h"
using extensions::mojom::APIPermissionID;
namespace extensions {
namespace errors = manifest_errors;
namespace {
// Helper object that is implicitly constructible from both a PermissionID and
// from an mojom::APIPermissionID.
struct PermissionIDCompareHelper {
PermissionIDCompareHelper(const PermissionID& id) : id(id.id()) {}
PermissionIDCompareHelper(const APIPermissionID id) : id(id) {}
APIPermissionID id;
};
bool CreateAPIPermission(const std::string& permission_str,
const base::Value* permission_value,
APIPermissionSet::ParseSource source,
APIPermissionSet* api_permissions,
std::u16string* error,
std::vector<std::string>* unhandled_permissions) {
const APIPermissionInfo* permission_info =
PermissionsInfo::GetInstance()->GetByName(permission_str);
if (permission_info) {
std::unique_ptr<APIPermission> permission(
permission_info->CreateAPIPermission());
if (source != APIPermissionSet::kAllowInternalPermissions &&
permission_info->is_internal()) {
// An internal permission specified in permissions list is an error.
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kPermissionNotAllowedInManifest, permission_str);
}
return false;
}
std::string error_details;
if (!permission->FromValue(permission_value, &error_details,
unhandled_permissions)) {
if (error) {
if (error_details.empty()) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermission,
permission_info->name());
} else {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermissionWithDetail,
permission_info->name(),
error_details);
}
return false;
}
VLOG(1) << "Parse permission failed.";
} else {
api_permissions->insert(std::move(permission));
}
return true;
}
if (unhandled_permissions)
unhandled_permissions->push_back(permission_str);
else
VLOG(1) << "Unknown permission[" << permission_str << "].";
return true;
}
bool ParseChildPermissions(const std::string& base_name,
const base::Value* permission_value,
APIPermissionSet::ParseSource source,
APIPermissionSet* api_permissions,
std::u16string* error,
std::vector<std::string>* unhandled_permissions) {
if (permission_value) {
if (!permission_value->is_list()) {
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermission, base_name);
return false;
}
VLOG(1) << "Permission value is not a list.";
// Failed to parse, but since error is NULL, failures are not fatal so
// return true here anyway.
return true;
}
base::Value::ConstListView list_view =
permission_value->GetListDeprecated();
for (size_t i = 0; i < list_view.size(); ++i) {
std::string permission_str;
if (!list_view[i].is_string()) {
// permission should be a string
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermission,
base_name + '.' + base::NumberToString(i));
return false;
}
VLOG(1) << "Permission is not a string.";
continue;
}
if (!CreateAPIPermission(base_name + '.' + list_view[i].GetString(),
nullptr, source, api_permissions, error,
unhandled_permissions))
return false;
}
}
return CreateAPIPermission(base_name, nullptr, source, api_permissions, error,
nullptr);
}
} // namespace
void APIPermissionSet::insert(APIPermissionID id) {
const APIPermissionInfo* permission_info =
PermissionsInfo::GetInstance()->GetByID(id);
DCHECK(permission_info);
insert(permission_info->CreateAPIPermission());
}
void APIPermissionSet::insert(std::unique_ptr<APIPermission> permission) {
BaseSetOperators<APIPermissionSet>::insert(std::move(permission));
}
// static
bool APIPermissionSet::ParseFromJSON(
const base::Value* permissions,
APIPermissionSet::ParseSource source,
APIPermissionSet* api_permissions,
std::u16string* error,
std::vector<std::string>* unhandled_permissions) {
if (!permissions->is_list()) {
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidPermission,
"<root>");
return false;
}
VLOG(1) << "Root Permissions value is not a list.";
// Failed to parse, but since error is NULL, failures are not fatal so
// return true here anyway.
return true;
}
base::Value::ConstListView list_view = permissions->GetListDeprecated();
for (size_t i = 0; i < list_view.size(); ++i) {
std::string permission_str;
const base::Value* permission_value = nullptr;
// permission should be a string or a single key dict.
if (list_view[i].is_string()) {
permission_str = list_view[i].GetString();
} else if (list_view[i].is_dict() && list_view[i].DictSize() == 1) {
auto dict_iter = list_view[i].DictItems().begin();
permission_str = dict_iter->first;
permission_value = &dict_iter->second;
} else {
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidPermission,
base::NumberToString(i));
return false;
}
VLOG(1) << "Permission is not a string or single key dict.";
continue;
}
// Check if this permission is a special case where its value should
// be treated as a list of child permissions.
if (PermissionsInfo::GetInstance()->HasChildPermissions(permission_str)) {
if (!ParseChildPermissions(permission_str, permission_value, source,
api_permissions, error, unhandled_permissions))
return false;
continue;
}
if (!CreateAPIPermission(permission_str, permission_value, source,
api_permissions, error, unhandled_permissions))
return false;
}
return true;
}
PermissionID::PermissionID(APIPermissionID id)
: std::pair<APIPermissionID, std::u16string>(id, std::u16string()) {}
PermissionID::PermissionID(APIPermissionID id, const std::u16string& parameter)
: std::pair<APIPermissionID, std::u16string>(id, parameter) {}
PermissionID::~PermissionID() {
}
PermissionIDSet::PermissionIDSet() {
}
PermissionIDSet::PermissionIDSet(
std::initializer_list<APIPermissionID> permissions) {
for (auto permission : permissions) {
permissions_.insert(PermissionID(permission));
}
}
PermissionIDSet::PermissionIDSet(const PermissionIDSet& other) = default;
PermissionIDSet::~PermissionIDSet() {
}
void PermissionIDSet::insert(APIPermissionID permission_id) {
insert(permission_id, std::u16string());
}
void PermissionIDSet::insert(APIPermissionID permission_id,
const std::u16string& permission_detail) {
permissions_.insert(PermissionID(permission_id, permission_detail));
}
void PermissionIDSet::InsertAll(const PermissionIDSet& permission_set) {
for (const auto& permission : permission_set.permissions_) {
permissions_.insert(permission);
}
}
void PermissionIDSet::erase(APIPermissionID permission_id) {
auto lower_bound = permissions_.lower_bound(PermissionID(permission_id));
auto upper_bound = lower_bound;
while (upper_bound != permissions_.end() &&
upper_bound->id() == permission_id) {
++upper_bound;
}
permissions_.erase(lower_bound, upper_bound);
}
std::vector<std::u16string> PermissionIDSet::GetAllPermissionParameters()
const {
std::vector<std::u16string> params;
for (const auto& permission : permissions_) {
params.push_back(permission.parameter());
}
return params;
}
bool PermissionIDSet::ContainsID(PermissionID permission_id) const {
auto it = permissions_.lower_bound(permission_id);
return it != permissions_.end() && it->id() == permission_id.id();
}
bool PermissionIDSet::ContainsID(APIPermissionID permission_id) const {
return ContainsID(PermissionID(permission_id));
}
bool PermissionIDSet::ContainsAllIDs(
const std::set<APIPermissionID>& permission_ids) const {
return std::includes(permissions_.begin(), permissions_.end(),
permission_ids.begin(), permission_ids.end(),
[] (const PermissionIDCompareHelper& lhs,
const PermissionIDCompareHelper& rhs) {
return lhs.id < rhs.id;
});
}
bool PermissionIDSet::ContainsAnyID(
const std::set<APIPermissionID>& permission_ids) const {
for (APIPermissionID id : permission_ids) {
if (ContainsID(id))
return true;
}
return false;
}
bool PermissionIDSet::ContainsAnyID(const PermissionIDSet& other) const {
for (const auto& id : other) {
if (ContainsID(id))
return true;
}
return false;
}
PermissionIDSet PermissionIDSet::GetAllPermissionsWithID(
APIPermissionID permission_id) const {
PermissionIDSet subset;
auto it = permissions_.lower_bound(PermissionID(permission_id));
while (it != permissions_.end() && it->id() == permission_id) {
subset.permissions_.insert(*it);
++it;
}
return subset;
}
PermissionIDSet PermissionIDSet::GetAllPermissionsWithIDs(
const std::set<APIPermissionID>& permission_ids) const {
PermissionIDSet subset;
for (const auto& permission : permissions_) {
if (base::Contains(permission_ids, permission.id())) {
subset.permissions_.insert(permission);
}
}
return subset;
}
bool PermissionIDSet::Includes(const PermissionIDSet& subset) const {
return base::ranges::includes(permissions_, subset.permissions_);
}
bool PermissionIDSet::Equals(const PermissionIDSet& set) const {
return permissions_ == set.permissions_;
}
// static
PermissionIDSet PermissionIDSet::Difference(const PermissionIDSet& set_1,
const PermissionIDSet& set_2) {
return PermissionIDSet(base::STLSetDifference<std::set<PermissionID>>(
set_1.permissions_, set_2.permissions_));
}
size_t PermissionIDSet::size() const {
return permissions_.size();
}
bool PermissionIDSet::empty() const {
return permissions_.empty();
}
PermissionIDSet::PermissionIDSet(const std::set<PermissionID>& permissions)
: permissions_(permissions) {
}
} // namespace extensions
| bsd-3-clause |
leighpauls/k2cro4 | third_party/ffmpeg/libavutil/Makefile | 8501 | include $(SUBDIR)../config.mak
NAME = avutil
HEADERS = adler32.h \
aes.h \
attributes.h \
audio_fifo.h \
audioconvert.h \
avassert.h \
avstring.h \
avutil.h \
base64.h \
blowfish.h \
bprint.h \
bswap.h \
common.h \
cpu.h \
crc.h \
error.h \
eval.h \
fifo.h \
file.h \
imgutils.h \
intfloat.h \
intfloat_readwrite.h \
intreadwrite.h \
lfg.h \
log.h \
lzo.h \
mathematics.h \
md5.h \
mem.h \
dict.h \
opt.h \
parseutils.h \
pixdesc.h \
pixfmt.h \
random_seed.h \
rational.h \
samplefmt.h \
sha.h \
time.h \
timecode.h \
timestamp.h \
version.h \
xtea.h \
ARCH_HEADERS = bswap.h \
intmath.h \
intreadwrite.h \
timer.h \
BUILT_HEADERS = avconfig.h
OBJS = adler32.o \
aes.o \
audio_fifo.o \
audioconvert.o \
avstring.o \
base64.o \
blowfish.o \
bprint.o \
cpu.o \
crc.o \
des.o \
error.o \
eval.o \
fifo.o \
file.o \
float_dsp.o \
imgutils.o \
intfloat_readwrite.o \
inverse.o \
lfg.o \
lls.o \
log.o \
lzo.o \
mathematics.o \
md5.o \
mem.o \
dict.o \
opt.o \
parseutils.o \
pixdesc.o \
random_seed.o \
rational.o \
rc4.o \
samplefmt.o \
sha.o \
time.o \
timecode.o \
tree.o \
utils.o \
xtea.o \
OBJS-$(HAVE_BROKEN_SNPRINTF) += ../compat/msvcrt/snprintf.o
OBJS-$(HAVE_MSVCRT) += ../compat/strtod.o
TESTPROGS = adler32 \
aes \
avstring \
base64 \
blowfish \
bprint \
cpu \
crc \
des \
error \
eval \
file \
fifo \
lfg \
lls \
md5 \
opt \
pca \
parseutils \
random_seed \
rational \
sha \
tree \
xtea \
TESTPROGS-$(HAVE_LZO1X_999_COMPRESS) += lzo
TOOLS = ffeval
$(SUBDIR)lzo-test$(EXESUF): ELIBS = -llzo2
| bsd-3-clause |
vsco/grpc | src/core/lib/iomgr/ev_poll_posix.h | 1913 | /*
*
* Copyright 2015-2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H
#define GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H
#include "src/core/lib/iomgr/ev_posix.h"
const grpc_event_engine_vtable *grpc_init_poll_posix(bool explicit_request);
const grpc_event_engine_vtable *grpc_init_poll_cv_posix(bool explicit_request);
#endif /* GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H */
| bsd-3-clause |
chromium/chromium | chrome/test/chromedriver/client/websocket_connection.py | 1471 | # Copyright 2019 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.
import os
import sys
import json
from command_executor import CommandExecutor
_THIS_DIR = os.path.abspath(os.path.dirname(__file__))
_PARENT_DIR = os.path.join(_THIS_DIR, os.pardir)
sys.path.insert(1, _PARENT_DIR)
import chrome_paths
sys.path.remove(_PARENT_DIR)
sys.path.insert(0,os.path.join(chrome_paths.GetSrc(), 'third_party',
'catapult', 'telemetry', 'third_party',
'websocket-client'))
import websocket
class WebSocketCommands:
CREATE_WEBSOCKET = \
'/session/:sessionId'
SEND_OVER_WEBSOCKET = \
'/session/:sessionId/chromium/send_command_from_websocket'
class WebSocketConnection(object):
def __init__(self, server_url, session_id):
self._server_url = server_url.replace('http', 'ws')
self._session_id = session_id
self._command_id = -1
cmd_params = {'sessionId': session_id}
path = CommandExecutor.CreatePath(
WebSocketCommands.CREATE_WEBSOCKET, cmd_params)
self._websocket = websocket.create_connection(self._server_url + path)
def SendCommand(self, cmd_params):
cmd_params['id'] = self._command_id
self._command_id -= 1
self._websocket.send(json.dumps(cmd_params))
def ReadMessage(self):
return self._websocket.recv()
def Close(self):
self._websocket.close();
| bsd-3-clause |
DuVale/snapboard | extras/registration/templates/registration/logout.html | 192 | {% extends "registration/base.html" %}
{% load i18n %}
{% block registration_content %}
{% trans "You have been logged out. Thank you for your visit and see you soon!" %}
{% endblock %}
| bsd-3-clause |
chromium/chromium | components/autofill/core/browser/payments/test_authentication_requester.cc | 2142 | // Copyright 2019 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.
#include "components/autofill/core/browser/payments/test_authentication_requester.h"
#include <string>
#include "build/build_config.h"
#include "components/autofill/core/browser/data_model/credit_card.h"
namespace autofill {
TestAuthenticationRequester::TestAuthenticationRequester() {}
TestAuthenticationRequester::~TestAuthenticationRequester() {}
base::WeakPtr<TestAuthenticationRequester>
TestAuthenticationRequester::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void TestAuthenticationRequester::OnCVCAuthenticationComplete(
const CreditCardCVCAuthenticator::CVCAuthenticationResponse& response) {
did_succeed_ = response.did_succeed;
if (*did_succeed_) {
DCHECK(response.card);
number_ = response.card->number();
}
}
#if BUILDFLAG(IS_ANDROID)
bool TestAuthenticationRequester::ShouldOfferFidoAuth() const {
return false;
}
bool TestAuthenticationRequester::UserOptedInToFidoFromSettingsPageOnMobile()
const {
return false;
}
#endif
#if !BUILDFLAG(IS_IOS)
void TestAuthenticationRequester::OnFIDOAuthenticationComplete(
const CreditCardFIDOAuthenticator::FidoAuthenticationResponse& response) {
did_succeed_ = response.did_succeed;
if (*did_succeed_) {
DCHECK(response.card);
number_ = response.card->number();
}
failure_type_ = response.failure_type;
}
void TestAuthenticationRequester::OnFidoAuthorizationComplete(
bool did_succeed) {
did_succeed_ = did_succeed;
}
void TestAuthenticationRequester::IsUserVerifiableCallback(
bool is_user_verifiable) {
is_user_verifiable_ = is_user_verifiable;
}
#endif
void TestAuthenticationRequester::OnOtpAuthenticationComplete(
const CreditCardOtpAuthenticator::OtpAuthenticationResponse& response) {
did_succeed_ =
response.result ==
CreditCardOtpAuthenticator::OtpAuthenticationResponse::Result::kSuccess;
if (*did_succeed_) {
DCHECK(response.card);
number_ = response.card->number();
}
}
} // namespace autofill
| bsd-3-clause |
NeuroRoboticTech/AnimatLabPublicSource | Libraries/VortexAnimatSim/Vortex_UnitTests/stdafx.cpp | 297 | // stdafx.cpp : source file that includes just the standard includes
// StdUtils_UnitTests.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| bsd-3-clause |
endlessm/chromium-browser | third_party/webrtc/test/layer_filtering_transport.h | 2470 | /*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef TEST_LAYER_FILTERING_TRANSPORT_H_
#define TEST_LAYER_FILTERING_TRANSPORT_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include "api/call/transport.h"
#include "api/media_types.h"
#include "call/call.h"
#include "call/simulated_packet_receiver.h"
#include "modules/rtp_rtcp/source/video_rtp_depacketizer.h"
#include "test/direct_transport.h"
namespace webrtc {
namespace test {
class LayerFilteringTransport : public test::DirectTransport {
public:
LayerFilteringTransport(
TaskQueueBase* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map,
uint32_t ssrc_to_filter_min,
uint32_t ssrc_to_filter_max);
LayerFilteringTransport(
TaskQueueBase* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map);
bool DiscardedLastPacket() const;
bool SendRtp(const uint8_t* data,
size_t length,
const PacketOptions& options) override;
private:
// Used to distinguish between VP8 and VP9.
const uint8_t vp8_video_payload_type_;
const uint8_t vp9_video_payload_type_;
const std::unique_ptr<VideoRtpDepacketizer> vp8_depacketizer_;
const std::unique_ptr<VideoRtpDepacketizer> vp9_depacketizer_;
// Discard or invalidate all temporal/spatial layers with id greater than the
// selected one. -1 to disable filtering.
const int selected_tl_;
const int selected_sl_;
bool discarded_last_packet_;
int num_active_spatial_layers_;
const uint32_t ssrc_to_filter_min_;
const uint32_t ssrc_to_filter_max_;
};
} // namespace test
} // namespace webrtc
#endif // TEST_LAYER_FILTERING_TRANSPORT_H_
| bsd-3-clause |
ryanrhymes/openblas | lib/OpenBLAS-0.2.19/lapack-netlib/LAPACKE/src/lapacke_dgeqlf.c | 3285 | /*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function dgeqlf
* Author: Intel Corporation
* Generated November 2015
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_dgeqlf( int matrix_layout, lapack_int m, lapack_int n,
double* a, lapack_int lda, double* tau )
{
lapack_int info = 0;
lapack_int lwork = -1;
double* work = NULL;
double work_query;
if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_dgeqlf", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
/* Optionally check input matrices for NaNs */
if( LAPACKE_dge_nancheck( matrix_layout, m, n, a, lda ) ) {
return -4;
}
#endif
/* Query optimal working array(s) size */
info = LAPACKE_dgeqlf_work( matrix_layout, m, n, a, lda, tau, &work_query,
lwork );
if( info != 0 ) {
goto exit_level_0;
}
lwork = (lapack_int)work_query;
/* Allocate memory for work arrays */
work = (double*)LAPACKE_malloc( sizeof(double) * lwork );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_dgeqlf_work( matrix_layout, m, n, a, lda, tau, work, lwork );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_dgeqlf", info );
}
return info;
}
| bsd-3-clause |
jens-maus/amissl | openssl/doc/man3/BN_security_bits.pod | 1496 | =pod
=head1 NAME
BN_security_bits - returns bits of security based on given numbers
=head1 SYNOPSIS
#include <openssl/bn.h>
int BN_security_bits(int L, int N);
=head1 DESCRIPTION
BN_security_bits() returns the number of bits of security provided by a
specific algorithm and a particular key size. The bits of security is
defined in NIST SP800-57. Currently, BN_security_bits() support two types
of asymmetric algorithms: the FFC (Finite Field Cryptography) and IFC
(Integer Factorization Cryptography). For FFC, e.g., DSA and DH, both
parameters B<L> and B<N> are used to decide the bits of security, where
B<L> is the size of the public key and B<N> is the size of the private
key. For IFC, e.g., RSA, only B<L> is used and it's commonly considered
to be the key size (modulus).
=head1 RETURN VALUES
Number of security bits.
=head1 NOTES
ECC (Elliptic Curve Cryptography) is not covered by the BN_security_bits()
function. The symmetric algorithms are not covered neither.
=head1 SEE ALSO
L<DH_security_bits(3)>, L<DSA_security_bits(3)>, L<RSA_security_bits(3)>
=head1 HISTORY
The BN_security_bits() function was added in OpenSSL 1.1.0.
=head1 COPYRIGHT
Copyright 2017-2019 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| bsd-3-clause |
CSE3320/kernel-code | linux-5.8/include/uapi/linux/can/error.h | 6625 | /* SPDX-License-Identifier: ((GPL-2.0-only WITH Linux-syscall-note) OR BSD-3-Clause) */
/*
* linux/can/error.h
*
* Definitions of the CAN error messages to be filtered and passed to the user.
*
* Author: Oliver Hartkopp <[email protected]>
* Copyright (c) 2002-2007 Volkswagen Group Electronic Research
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Volkswagen nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, provided that this notice is retained in full, this
* software may be distributed under the terms of the GNU General
* Public License ("GPL") version 2, in which case the provisions of the
* GPL apply INSTEAD OF those given above.
*
* The provided data structures and external interfaces from this code
* are not restricted to be used by modules with a GPL compatible license.
*
* 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 _UAPI_CAN_ERROR_H
#define _UAPI_CAN_ERROR_H
#define CAN_ERR_DLC 8 /* dlc for error message frames */
/* error class (mask) in can_id */
#define CAN_ERR_TX_TIMEOUT 0x00000001U /* TX timeout (by netdevice driver) */
#define CAN_ERR_LOSTARB 0x00000002U /* lost arbitration / data[0] */
#define CAN_ERR_CRTL 0x00000004U /* controller problems / data[1] */
#define CAN_ERR_PROT 0x00000008U /* protocol violations / data[2..3] */
#define CAN_ERR_TRX 0x00000010U /* transceiver status / data[4] */
#define CAN_ERR_ACK 0x00000020U /* received no ACK on transmission */
#define CAN_ERR_BUSOFF 0x00000040U /* bus off */
#define CAN_ERR_BUSERROR 0x00000080U /* bus error (may flood!) */
#define CAN_ERR_RESTARTED 0x00000100U /* controller restarted */
/* arbitration lost in bit ... / data[0] */
#define CAN_ERR_LOSTARB_UNSPEC 0x00 /* unspecified */
/* else bit number in bitstream */
/* error status of CAN-controller / data[1] */
#define CAN_ERR_CRTL_UNSPEC 0x00 /* unspecified */
#define CAN_ERR_CRTL_RX_OVERFLOW 0x01 /* RX buffer overflow */
#define CAN_ERR_CRTL_TX_OVERFLOW 0x02 /* TX buffer overflow */
#define CAN_ERR_CRTL_RX_WARNING 0x04 /* reached warning level for RX errors */
#define CAN_ERR_CRTL_TX_WARNING 0x08 /* reached warning level for TX errors */
#define CAN_ERR_CRTL_RX_PASSIVE 0x10 /* reached error passive status RX */
#define CAN_ERR_CRTL_TX_PASSIVE 0x20 /* reached error passive status TX */
/* (at least one error counter exceeds */
/* the protocol-defined level of 127) */
#define CAN_ERR_CRTL_ACTIVE 0x40 /* recovered to error active state */
/* error in CAN protocol (type) / data[2] */
#define CAN_ERR_PROT_UNSPEC 0x00 /* unspecified */
#define CAN_ERR_PROT_BIT 0x01 /* single bit error */
#define CAN_ERR_PROT_FORM 0x02 /* frame format error */
#define CAN_ERR_PROT_STUFF 0x04 /* bit stuffing error */
#define CAN_ERR_PROT_BIT0 0x08 /* unable to send dominant bit */
#define CAN_ERR_PROT_BIT1 0x10 /* unable to send recessive bit */
#define CAN_ERR_PROT_OVERLOAD 0x20 /* bus overload */
#define CAN_ERR_PROT_ACTIVE 0x40 /* active error announcement */
#define CAN_ERR_PROT_TX 0x80 /* error occurred on transmission */
/* error in CAN protocol (location) / data[3] */
#define CAN_ERR_PROT_LOC_UNSPEC 0x00 /* unspecified */
#define CAN_ERR_PROT_LOC_SOF 0x03 /* start of frame */
#define CAN_ERR_PROT_LOC_ID28_21 0x02 /* ID bits 28 - 21 (SFF: 10 - 3) */
#define CAN_ERR_PROT_LOC_ID20_18 0x06 /* ID bits 20 - 18 (SFF: 2 - 0 )*/
#define CAN_ERR_PROT_LOC_SRTR 0x04 /* substitute RTR (SFF: RTR) */
#define CAN_ERR_PROT_LOC_IDE 0x05 /* identifier extension */
#define CAN_ERR_PROT_LOC_ID17_13 0x07 /* ID bits 17-13 */
#define CAN_ERR_PROT_LOC_ID12_05 0x0F /* ID bits 12-5 */
#define CAN_ERR_PROT_LOC_ID04_00 0x0E /* ID bits 4-0 */
#define CAN_ERR_PROT_LOC_RTR 0x0C /* RTR */
#define CAN_ERR_PROT_LOC_RES1 0x0D /* reserved bit 1 */
#define CAN_ERR_PROT_LOC_RES0 0x09 /* reserved bit 0 */
#define CAN_ERR_PROT_LOC_DLC 0x0B /* data length code */
#define CAN_ERR_PROT_LOC_DATA 0x0A /* data section */
#define CAN_ERR_PROT_LOC_CRC_SEQ 0x08 /* CRC sequence */
#define CAN_ERR_PROT_LOC_CRC_DEL 0x18 /* CRC delimiter */
#define CAN_ERR_PROT_LOC_ACK 0x19 /* ACK slot */
#define CAN_ERR_PROT_LOC_ACK_DEL 0x1B /* ACK delimiter */
#define CAN_ERR_PROT_LOC_EOF 0x1A /* end of frame */
#define CAN_ERR_PROT_LOC_INTERM 0x12 /* intermission */
/* error status of CAN-transceiver / data[4] */
/* CANH CANL */
#define CAN_ERR_TRX_UNSPEC 0x00 /* 0000 0000 */
#define CAN_ERR_TRX_CANH_NO_WIRE 0x04 /* 0000 0100 */
#define CAN_ERR_TRX_CANH_SHORT_TO_BAT 0x05 /* 0000 0101 */
#define CAN_ERR_TRX_CANH_SHORT_TO_VCC 0x06 /* 0000 0110 */
#define CAN_ERR_TRX_CANH_SHORT_TO_GND 0x07 /* 0000 0111 */
#define CAN_ERR_TRX_CANL_NO_WIRE 0x40 /* 0100 0000 */
#define CAN_ERR_TRX_CANL_SHORT_TO_BAT 0x50 /* 0101 0000 */
#define CAN_ERR_TRX_CANL_SHORT_TO_VCC 0x60 /* 0110 0000 */
#define CAN_ERR_TRX_CANL_SHORT_TO_GND 0x70 /* 0111 0000 */
#define CAN_ERR_TRX_CANL_SHORT_TO_CANH 0x80 /* 1000 0000 */
/* controller specific additional information / data[5..7] */
#endif /* _UAPI_CAN_ERROR_H */
| gpl-2.0 |
willglynn/go-ipfs | p2p/protocol/ping/ping.go | 1786 | package ping
import (
"bytes"
"errors"
"io"
"time"
context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
host "github.com/ipfs/go-ipfs/p2p/host"
inet "github.com/ipfs/go-ipfs/p2p/net"
peer "github.com/ipfs/go-ipfs/p2p/peer"
logging "github.com/ipfs/go-ipfs/vendor/go-log-v1.0.0"
u "github.com/ipfs/go-ipfs/util"
)
var log = logging.Logger("ping")
const PingSize = 32
const ID = "/ipfs/ping"
type PingService struct {
Host host.Host
}
func NewPingService(h host.Host) *PingService {
ps := &PingService{h}
h.SetStreamHandler(ID, ps.PingHandler)
return ps
}
func (p *PingService) PingHandler(s inet.Stream) {
buf := make([]byte, PingSize)
for {
_, err := io.ReadFull(s, buf)
if err != nil {
log.Debug(err)
return
}
_, err = s.Write(buf)
if err != nil {
log.Debug(err)
return
}
}
}
func (ps *PingService) Ping(ctx context.Context, p peer.ID) (<-chan time.Duration, error) {
s, err := ps.Host.NewStream(ID, p)
if err != nil {
return nil, err
}
out := make(chan time.Duration)
go func() {
defer close(out)
for {
select {
case <-ctx.Done():
return
default:
t, err := ping(s)
if err != nil {
log.Debugf("ping error: %s", err)
return
}
select {
case out <- t:
case <-ctx.Done():
return
}
}
}
}()
return out, nil
}
func ping(s inet.Stream) (time.Duration, error) {
buf := make([]byte, PingSize)
u.NewTimeSeededRand().Read(buf)
before := time.Now()
_, err := s.Write(buf)
if err != nil {
return 0, err
}
rbuf := make([]byte, PingSize)
_, err = io.ReadFull(s, rbuf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf, rbuf) {
return 0, errors.New("ping packet was incorrect!")
}
return time.Now().Sub(before), nil
}
| mit |
j-f1/forked-desktop | app/src/ui/diff/image-diffs/onion-skin.tsx | 2059 | import * as React from 'react'
import { ICommonImageDiffProperties } from './modified-image-diff'
import { ImageContainer } from './image-container'
interface IOnionSkinState {
readonly crossfade: number
}
export class OnionSkin extends React.Component<
ICommonImageDiffProperties,
IOnionSkinState
> {
public constructor(props: ICommonImageDiffProperties) {
super(props)
this.state = { crossfade: 1 }
}
public render() {
const style: React.CSSProperties = {
height: this.props.maxSize.height,
width: this.props.maxSize.width,
}
const maxSize: React.CSSProperties = {
maxHeight: this.props.maxSize.height,
maxWidth: this.props.maxSize.width,
}
return (
<div className="image-diff-onion-skin">
<div className="sizing-container" ref={this.props.onContainerRef}>
<div className="image-container" style={style}>
<div className="image-diff-previous" style={style}>
<ImageContainer
image={this.props.previous}
onElementLoad={this.props.onPreviousImageLoad}
style={maxSize}
/>
</div>
<div
className="image-diff-current"
style={{
...style,
opacity: this.state.crossfade,
}}
>
<ImageContainer
image={this.props.current}
onElementLoad={this.props.onCurrentImageLoad}
style={maxSize}
/>
</div>
</div>
</div>
<input
style={{
width: this.props.maxSize.width / 2,
}}
className="slider"
type="range"
max={1}
min={0}
value={this.state.crossfade}
step={0.001}
onChange={this.onValueChange}
/>
</div>
)
}
private onValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ crossfade: e.currentTarget.valueAsNumber })
}
}
| mit |
hexojs/hexo-util | scripts/build_highlight_alias.js | 583 | 'use strict';
const hljs = require('highlight.js');
const languages = hljs.listLanguages();
const fs = require('fs');
const result = {
languages: languages,
aliases: {}
};
languages.forEach(lang => {
result.aliases[lang] = lang;
const def = require('highlight.js/lib/languages/' + lang)(hljs);
const aliases = def.aliases;
if (aliases) {
aliases.forEach(alias => {
result.aliases[alias] = lang;
});
}
});
const stream = fs.createWriteStream('highlight_alias.json');
stream.write(JSON.stringify(result));
stream.on('end', () => {
stream.end();
});
| mit |
suvjunmd/ScintillaNET | src/ScintillaNET/DoubleClickEventArgs.cs | 2400 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ScintillaNET
{
/// <summary>
/// Provides data for the <see cref="Scintilla.DoubleClick" /> event.
/// </summary>
public class DoubleClickEventArgs : EventArgs
{
private readonly Scintilla scintilla;
private readonly int bytePosition;
private int? position;
/// <summary>
/// Gets the line double clicked.
/// </summary>
/// <returns>The zero-based index of the double clicked line.</returns>
public int Line { get; private set; }
/// <summary>
/// Gets the modifier keys (SHIFT, CTRL, ALT) held down when double clicked.
/// </summary>
/// <returns>A bitwise combination of the Keys enumeration indicating the modifier keys.</returns>
public Keys Modifiers { get; private set; }
/// <summary>
/// Gets the zero-based document position of the text double clicked.
/// </summary>
/// <returns>
/// The zero-based character position within the document of the double clicked text;
/// otherwise, -1 if not a document position.
/// </returns>
public int Position
{
get
{
if (position == null)
position = scintilla.Lines.ByteToCharPosition(bytePosition);
return (int)position;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DoubleClickEventArgs" /> class.
/// </summary>
/// <param name="scintilla">The <see cref="Scintilla" /> control that generated this event.</param>
/// <param name="modifiers">The modifier keys that where held down at the time of the double click.</param>
/// <param name="bytePosition">The zero-based byte position of the double clicked text.</param>
/// <param name="line">The zero-based line index of the double clicked text.</param>
public DoubleClickEventArgs(Scintilla scintilla, Keys modifiers, int bytePosition, int line)
{
this.scintilla = scintilla;
this.bytePosition = bytePosition;
Modifiers = modifiers;
Line = line;
if (bytePosition == -1)
position = -1;
}
}
}
| mit |
t-zuehlsdorff/gitlabhq | lib/gitlab/slash_commands/issue_show.rb | 529 | module Gitlab
module SlashCommands
class IssueShow < IssueCommand
def self.match(text)
/\Aissue\s+show\s+#{Issue.reference_prefix}?(?<iid>\d+)/.match(text)
end
def self.help_message
"issue show <id>"
end
def execute(match)
issue = find_by_iid(match[:iid])
if issue
Gitlab::SlashCommands::Presenters::IssueShow.new(issue).present
else
Gitlab::SlashCommands::Presenters::Access.new.not_found
end
end
end
end
end
| mit |
mabotech/maboss-admin | public/kanban/scripts/directives/sortable.js | 8434 | 'use strict';
/*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('mpk').value('uiSortableConfig',{}).directive('uiSortable', [
'uiSortableConfig', '$timeout', '$log',
function(uiSortableConfig, $timeout, $log) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var savedNodes;
function combineCallbacks(first,second){
if(second && (typeof second === 'function')) {
return function(e, ui) {
first(e, ui);
second(e, ui);
};
}
return first;
}
var opts = {};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
angular.extend(opts, uiSortableConfig);
if (ngModel) {
// When we add or remove elements, we need the sortable to 'refresh'
// so it can find the new/removed elements.
scope.$watch(attrs.ngModel+'.length', function() {
// Timeout to let ng-repeat modify the DOM
$timeout(function() {
element.sortable('refresh');
});
});
callbacks.start = function(e, ui) {
// Save the starting position of dragged item
ui.item.sortable = {
index: ui.item.index(),
cancel: function () {
ui.item.sortable._isCanceled = true;
},
isCanceled: function () {
return ui.item.sortable._isCanceled;
},
_isCanceled: false
};
};
callbacks.activate = function(/*e, ui*/) {
// We need to make a copy of the current element's contents so
// we can restore it after sortable has messed it up.
// This is inside activate (instead of start) in order to save
// both lists when dragging between connected lists.
savedNodes = element.contents();
// If this list has a placeholder (the connected lists won't),
// don't inlcude it in saved nodes.
var placeholder = element.sortable('option','placeholder');
// placeholder.element will be a function if the placeholder, has
// been created (placeholder will be an object). If it hasn't
// been created, either placeholder will be false if no
// placeholder class was given or placeholder.element will be
// undefined if a class was given (placeholder will be a string)
if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
var phElement = placeholder.element();
// workaround for jquery ui 1.9.x,
// not returning jquery collection
if (!phElement.jquery) {
phElement = angular.element(phElement);
}
// exact match with the placeholder's class attribute to handle
// the case that multiple connected sortables exist and
// the placehoilder option equals the class of sortable items
var excludes = element.find('[class="' + phElement.attr('class') + '"]');
savedNodes = savedNodes.not(excludes);
}
};
callbacks.update = function(e, ui) {
// Save current drop position but only if this is not a second
// update that happens when moving between lists because then
// the value will be overwritten with the old value
if(!ui.item.sortable.received) {
ui.item.sortable.dropindex = ui.item.index();
ui.item.sortable.droptarget = ui.item.parent();
// Cancel the sort (let ng-repeat do the sort for us)
// Don't cancel if this is the received list because it has
// already been canceled in the other list, and trying to cancel
// here will mess up the DOM.
element.sortable('cancel');
}
// Put the nodes back exactly the way they started (this is very
// important because ng-repeat uses comment elements to delineate
// the start and stop of repeat sections and sortable doesn't
// respect their order (even if we cancel, the order of the
// comments are still messed up).
savedNodes.detach();
if (element.sortable('option','helper') === 'clone') {
// first detach all the savedNodes and then restore all of them
// except .ui-sortable-helper element (which is placed last).
// That way it will be garbage collected.
savedNodes = savedNodes.not(savedNodes.last());
}
savedNodes.appendTo(element);
// If received is true (an item was dropped in from another list)
// then we add the new item to this list otherwise wait until the
// stop event where we will know if it was a sort or item was
// moved here from another list
if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
ui.item.sortable.moved);
});
}
};
callbacks.stop = function(e, ui) {
// If the received flag hasn't be set on the item, this is a
// normal sort, if dropindex is set, the item was moved, so move
// the items in the list.
if(!ui.item.sortable.received &&
('dropindex' in ui.item.sortable) &&
!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ngModel.$modelValue.splice(
ui.item.sortable.dropindex, 0,
ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
});
} else {
// if the item was not moved, then restore the elements
// so that the ngRepeat's comment are correct.
if((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) && element.sortable('option','helper') !== 'clone') {
savedNodes.detach().appendTo(element);
}
}
};
callbacks.receive = function(e, ui) {
// An item was dropped here from another list, set a flag on the
// item.
ui.item.sortable.received = true;
};
callbacks.remove = function(e, ui) {
// Remove the item from this list's model and copy data into item,
// so the next list can retrive it
if (!ui.item.sortable.isCanceled()) {
scope.$apply(function () {
ui.item.sortable.moved = ngModel.$modelValue.splice(
ui.item.sortable.index, 1)[0];
});
}
};
scope.$watch(attrs.uiSortable, function(newVal /*, oldVal*/) {
angular.forEach(newVal, function(value, key) {
if(callbacks[key]) {
if( key === 'stop' ){
// call apply after stop
value = combineCallbacks(
value, function() { scope.$apply(); });
}
// wrap the callback
value = combineCallbacks(callbacks[key], value);
}
element.sortable('option', key, value);
});
}, true);
angular.forEach(callbacks, function(value, key) {
opts[key] = combineCallbacks(value, opts[key]);
});
} else {
$log.info('ui.sortable: ngModel not provided!', element);
}
// Create sortable
element.sortable(opts);
}
};
}
]);
| mit |
GabrieleCastellani/SCAMP | ProvisioningLibrary/VolatileStorage/GroupBudgetState.cs | 755 | using System;
using ProvisioningLibrary;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace ProvisioningLibrary
{
public class GroupBudgetState : TableEntity
{
private string _ResourceId = string.Empty;
public GroupBudgetState()
{
}
public GroupBudgetState(string groupId) : this()
{
this.RowKey = groupId;
this.PartitionKey = groupId;
}
public string GroupId {
get
{
return this.PartitionKey;
}
}
public long UnitsBudgetted { get; set; }
public long UnitsAllocated { get; set; }
public long UnitsUsed { get; set; }
}
}
| mit |
hansbonini/cloud9-magento | www/app/code/core/Mage/GoogleBase/Model/Item.php | 12442 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_GoogleBase
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Google Base Item Types Model
*
* @method Mage_GoogleBase_Model_Resource_Item _getResource()
* @method Mage_GoogleBase_Model_Resource_Item getResource()
* @method int getTypeId()
* @method Mage_GoogleBase_Model_Item setTypeId(int $value)
* @method int getProductId()
* @method Mage_GoogleBase_Model_Item setProductId(int $value)
* @method string getGbaseItemId()
* @method Mage_GoogleBase_Model_Item setGbaseItemId(string $value)
* @method int getStoreId()
* @method Mage_GoogleBase_Model_Item setStoreId(int $value)
* @method string getPublished()
* @method Mage_GoogleBase_Model_Item setPublished(string $value)
* @method string getExpires()
* @method Mage_GoogleBase_Model_Item setExpires(string $value)
* @method int getImpr()
* @method Mage_GoogleBase_Model_Item setImpr(int $value)
* @method int getClicks()
* @method Mage_GoogleBase_Model_Item setClicks(int $value)
* @method int getViews()
* @method Mage_GoogleBase_Model_Item setViews(int $value)
* @method int getIsHidden()
* @method Mage_GoogleBase_Model_Item setIsHidden(int $value)
*
* @deprecated after 1.5.1.0
* @category Mage
* @package Mage_GoogleBase
* @author Magento Core Team <[email protected]>
*/
class Mage_GoogleBase_Model_Item extends Mage_Core_Model_Abstract
{
const ATTRIBUTES_REGISTRY_KEY = 'gbase_attributes_registry';
const TYPES_REGISTRY_KEY = 'gbase_types_registry';
protected function _construct()
{
parent::_construct();
$this->_init('googlebase/item');
}
/**
* Return Service Item Instance
*
* @return Mage_GoogleBase_Model_Service_Item
*/
public function getServiceItem()
{
return Mage::getModel('googlebase/service_item')->setStoreId($this->getStoreId());
}
/**
* Target Country
*
* @return string Two-letters country ISO code
*/
public function getTargetCountry()
{
return Mage::getSingleton('googlebase/config')->getTargetCountry($this->getStoreId());
}
/**
* Save item to Google Base
*
* @return Mage_GoogleBase_Model_Item
*/
public function insertItem()
{
$this->_checkProduct()
->_prepareProductObject();
$typeModel = $this->_getTypeModel();
$this->getServiceItem()
->setItem($this)
->setObject($this->getProduct())
->setAttributeValues($this->_getAttributeValues())
->setItemType($typeModel->getGbaseItemtype())
->insert();
$this->setTypeId($typeModel->getTypeId());
return $this;
}
/**
* Update Item data
*
* @return Mage_GoogleBase_Model_Item
*/
public function updateItem()
{
$this->_checkProduct()
->_prepareProductObject();
$this->loadByProduct($this->getProduct());
if ($this->getId()) {
$typeModel = $this->_getTypeModel();
$this->getServiceItem()
->setItem($this)
->setObject($this->getProduct())
->setAttributeValues($this->_getAttributeValues())
->setItemType($typeModel->getGbaseItemtype())
->update();
}
return $this;
}
/**
* Delete Item from Google Base
*
* @return Mage_GoogleBase_Model_Item
*/
public function deleteItem()
{
$this->getServiceItem()->setItem($this)->delete();
return $this;
}
/**
* Delete Item from Google Base
*
* @return Mage_GoogleBase_Model_Item
*/
public function hideItem()
{
$this->getServiceItem()->setItem($this)->hide();
$this->setIsHidden(1);
$this->save();
return $this;
}
/**
* Delete Item from Google Base
*
* @return Mage_GoogleBase_Model_Item
*/
public function activateItem()
{
$this->getServiceItem()->setItem($this)->activate();
$this->setIsHidden(0);
$this->save();
return $this;
}
/**
* Load Item Model by Product
*
* @param Mage_Catalog_Model_Product $product
* @return Mage_GoogleBase_Model_Item
*/
public function loadByProduct($product)
{
if (!$this->getProduct()) {
$this->setProduct($product);
}
$this->getResource()->loadByProduct($this);
return $this;
}
/**
* Product Setter
*
* @param Mage_Catalog_Model_Product
* @return Mage_GoogleBase_Model_Item
*/
public function setProduct($product)
{
if (!($product instanceof Mage_Catalog_Model_Product)) {
Mage::throwException(Mage::helper('googlebase')->__('Invalid Product Model for Google Base Item'));
}
$this->setData('product', $product);
$this->setProductId($product->getId());
$this->setStoreId($product->getStoreId());
return $this;
}
/**
* Check product instance
*
* @return Mage_GoogleBase_Model_Item
*/
protected function _checkProduct()
{
if (!($this->getProduct() instanceof Mage_Catalog_Model_Product)) {
Mage::throwException(Mage::helper('googlebase')->__('Invalid Product Model for Google Base Item'));
}
return $this;
}
/**
* Copy Product object and assign additional data to the copy
*
* @return Mage_GoogleBase_Model_Item
*/
protected function _prepareProductObject()
{
$product = clone $this->getProduct();
/* @var $product Mage_Catalog_Model_Product */
$url = $product->getProductUrl(false);
if (!Mage::getStoreConfigFlag('web/url/use_store')) {
$urlInfo = parse_url($url);
$store = $product->getStore()->getCode();
if (isset($urlInfo['query']) && $urlInfo['query'] != '') {
$url .= '&___store=' . $store;
} else {
$url .= '?___store=' . $store;
}
}
$product->setUrl($url)
->setQuantity( $this->getProduct()->getStockItem()->getQty() )
->setImageUrl( Mage::helper('catalog/product')->getImageUrl($product) );
$this->setProduct($product);
return $this;
}
/**
* Return Product attribute values array
*
* @return array Product attribute values
*/
protected function _getAttributeValues()
{
$result = array();
$productAttributes = $this->_getProductAttributes();
foreach ($this->_getAttributesCollection() as $attribute) {
$attributeId = $attribute->getAttributeId();
if (isset($productAttributes[$attributeId])) {
$productAttribute = $productAttributes[$attributeId];
if ($attribute->getGbaseAttribute()) {
$name = $attribute->getGbaseAttribute();
} else {
$name = $this->_getAttributeLabel($productAttribute, $this->getProduct()->getStoreId());
}
$value = $productAttribute->getGbaseValue();
$type = Mage::getSingleton('googlebase/attribute')->getGbaseAttributeType($productAttribute);
if ($name && $value && $type) {
$result[$name] = array(
'value' => $value,
'type' => $type
);
}
}
}
return $result;
}
/**
* Return Product Attribute Store Label
*
* @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
* @param int $storeId Store View Id
* @return string Attribute Store View Label or Attribute code
*/
protected function _getAttributeLabel($attribute, $storeId)
{
$frontendLabel = $attribute->getFrontend()->getLabel();
if (is_array($frontendLabel)) {
$frontendLabel = array_shift($frontendLabel);
}
if (!$this->_translations) {
$moduleName = Mage_Catalog_Model_Entity_Attribute::MODULE_NAME;
$separator = Mage_Core_Model_Translate::SCOPE_SEPARATOR;
$this->_translations = Mage::getModel('core/translate_string')
->load($moduleName . $separator . $frontendLabel)
->getStoreTranslations();
}
if (isset($this->_translations[$storeId])) {
return $this->_translations[$storeId];
} else {
return $attribute->getAttributeCode();
}
}
/**
* Return Google Base Item Type Model for current Product Attribute Set
*
* @return Mage_GoogleBase_Model_Type
*/
protected function _getTypeModel()
{
$registry = Mage::registry(self::TYPES_REGISTRY_KEY);
$attributeSetId = $this->getProduct()->getAttributeSetId();
if (is_array($registry) && isset($registry[$attributeSetId])) {
return $registry[$attributeSetId];
}
$model = Mage::getModel('googlebase/type')->loadByAttributeSetId($attributeSetId, $this->getTargetCountry());
$registry[$attributeSetId] = $model;
Mage::unregister(self::TYPES_REGISTRY_KEY);
Mage::register(self::TYPES_REGISTRY_KEY, $registry);
return $model;
}
/**
* Return Product attributes array
*
* @return array Product attributes
*/
protected function _getProductAttributes()
{
$product = $this->getProduct();
$attributes = $product->getAttributes();
$result = array();
foreach ($attributes as $attribute) {
$value = $attribute->getFrontend()->getValue($product);
if (is_string($value) && strlen($value) && $product->hasData($attribute->getAttributeCode())) {
$attribute->setGbaseValue($value);
$result[$attribute->getAttributeId()] = $attribute;
}
}
return $result;
}
/**
* Get Product Media files info
*
* @return array Media files info
*/
protected function _getProductImages()
{
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');
if (!isset($galleryData['images']) || !is_array($galleryData['images'])) {
return array();
}
$result = array();
foreach ($galleryData['images'] as $image) {
$image['url'] = Mage::getSingleton('catalog/product_media_config')
->getMediaUrl($image['file']);
$result[] = $image;
}
return $result;
}
/**
* Return attribute collection for current Product Attribute Set
*
* @return Mage_GoogleBase_Model_Mysql4_Attribute_Collection
*/
protected function _getAttributesCollection()
{
$registry = Mage::registry(self::ATTRIBUTES_REGISTRY_KEY);
$attributeSetId = $this->getProduct()->getAttributeSetId();
if (is_array($registry) && isset($registry[$attributeSetId])) {
return $registry[$attributeSetId];
}
$collection = Mage::getResourceModel('googlebase/attribute_collection')
->addAttributeSetFilter($attributeSetId, $this->getTargetCountry())
->load();
$registry[$attributeSetId] = $collection;
Mage::unregister(self::ATTRIBUTES_REGISTRY_KEY);
Mage::register(self::ATTRIBUTES_REGISTRY_KEY, $registry);
return $collection;
}
}
| mit |
showdownjs/showdown | test/functional/makemarkdown/cases/standard/emphasis-inside-inline-code.md | 20 | some text `**foo**`
| mit |
jingwug/public | phalcon2/cphalcon/ext/phalcon/events/exception.zep.h | 102 |
extern zend_class_entry *phalcon_events_exception_ce;
ZEPHIR_INIT_CLASS(Phalcon_Events_Exception);
| mit |
enclose-io/compiler | lts/deps/v8/src/snapshot/roots-serializer.cc | 2307 | // Copyright 2018 the V8 project 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 "src/snapshot/roots-serializer.h"
#include "src/execution/isolate.h"
#include "src/heap/heap.h"
#include "src/objects/objects-inl.h"
#include "src/objects/slots.h"
namespace v8 {
namespace internal {
RootsSerializer::RootsSerializer(Isolate* isolate,
RootIndex first_root_to_be_serialized)
: Serializer(isolate),
first_root_to_be_serialized_(first_root_to_be_serialized),
can_be_rehashed_(true) {
for (size_t i = 0; i < static_cast<size_t>(first_root_to_be_serialized);
++i) {
root_has_been_serialized_[i] = true;
}
}
int RootsSerializer::SerializeInObjectCache(HeapObject heap_object) {
int index;
if (!object_cache_index_map_.LookupOrInsert(heap_object, &index)) {
// This object is not part of the object cache yet. Add it to the cache so
// we can refer to it via cache index from the delegating snapshot.
SerializeObject(heap_object);
}
return index;
}
void RootsSerializer::Synchronize(VisitorSynchronization::SyncTag tag) {
sink_.Put(kSynchronize, "Synchronize");
}
void RootsSerializer::VisitRootPointers(Root root, const char* description,
FullObjectSlot start,
FullObjectSlot end) {
RootsTable& roots_table = isolate()->roots_table();
if (start ==
roots_table.begin() + static_cast<int>(first_root_to_be_serialized_)) {
// Serializing the root list needs special handling:
// - Only root list elements that have been fully serialized can be
// referenced using kRootArray bytecodes.
for (FullObjectSlot current = start; current < end; ++current) {
SerializeRootObject(*current);
size_t root_index = current - roots_table.begin();
root_has_been_serialized_.set(root_index);
}
} else {
Serializer::VisitRootPointers(root, description, start, end);
}
}
void RootsSerializer::CheckRehashability(HeapObject obj) {
if (!can_be_rehashed_) return;
if (!obj.NeedsRehashing()) return;
if (obj.CanBeRehashed()) return;
can_be_rehashed_ = false;
}
} // namespace internal
} // namespace v8
| mit |
cybercircuits/jQTouch | demos/ext_autotitles/index.html | 1707 | <!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>jQT.AutoTitles</title>
<style type="text/css" media="screen">@import "../../themes/css/jqtouch.css";</style>
<script src="../../lib/zepto/zepto.js" type="text/javascript" charset="utf-8"></script>
<script src="../../src/jqt.js" type="text/javascript" charset="utf-8"></script>
<script src="../../extensions/jqt.autotitles.js" type="application/x-javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var jQT = new $.jQT({
icon: 'jqtouch.png',
addGlossToIcon: false,
startupScreen: 'jqt_startup.png',
statusBar: 'black'
});
</script>
</head>
<body>
<div id="jqt">
<div id="page1">
<div class="toolbar">
<h1>Auto Titles</h1>
</div>
<ul class="edgetoedge">
<li><a href="#page2">Oranges</a></li>
<li><a href="#page2">Bananas</a></li>
<li><a href="#page2">Apples</a></li>
</ul>
</div>
<div id="page2">
<div class="toolbar">
<a href="#" class="back">back</a>
<h1><!-- Will be filled in --></h1>
</div>
<div class="info">
The title for this page was automatically set from it’s referring link, no extra scripts required. Just include the extension and this happens.
</div>
</div>
</div>
</body>
</html>
| mit |
burakkp/code-guide | index.html | 20948 | ---
layout: default
---
<div class="heading" id="toc">
<h2>Table of contents</h2>
</div>
<div class="section toc">
<div class="col">
<h4><a href="#html">HTML</a></h4>
<ul>
<li><a href="#html-syntax">Syntax</a></li>
<li><a href="#html-doctype">HTML5 doctype</a></li>
<li><a href="#html-lang">Language attribute</a></li>
<li><a href="#html-encoding">Character encoding</a></li>
<li><a href="#html-ie-compatibility-mode">Internet Explorer compatibility mode</a></li>
<li><a href="#html-style-script">CSS and JavaScript includes</a></li>
<li><a href="#html-practicality">Practicality over purity</a></li>
<li><a href="#html-attribute-order">Attribute order</a></li>
<li><a href="#html-boolean-attributes">Boolean attributes</a></li>
<li><a href="#html-reducing-markup">Reducing markup</a></li>
<li><a href="#html-javascript">JavaScript generated markup</a></li>
</ul>
</div>
<div class="col">
<h4><a href="#css">CSS</a></h4>
<ul>
<li><a href="#css-syntax">CSS syntax</a></li>
<li><a href="#css-declaration-order">Declaration order</a></li>
<li><a href="#css-import">Don't use @import</a></li>
<li><a href="#css-media-queries">Media query placement</a></li>
<li><a href="#css-prefixed-properties">Prefixed properties</a></li>
<li><a href="#css-single-declarations">Rules with single declarations</a></li>
<li><a href="#css-shorthand">Shorthand notation</a></li>
<li><a href="#css-nesting">Nesting in Less and Sass</a></li>
<li><a href="#css-comments">Comments</a></li>
<li><a href="#css-classes">Classes</a></li>
<li><a href="#css-selectors">Selectors</a></li>
<li><a href="#css-organization">Organization</a></li>
</ul>
</div>
</div>
<div class="section" id="golden-rule">
<div class="col">
<h2>Golden rule</h2>
<p>Enforce these, or your own, agreed upon guidelines at all times. Small or large, call out what's incorrect. For additions or contributions to this Code Guide, please <a href="https://github.com/mdo/code-guide/issues/new">open an issue on GitHub</a>.</p>
</div>
<div class="col">
<blockquote>
<p>Every line of code should appear to be written by a single person, no matter the number of contributors.</p>
</blockquote>
</div>
</div>
<div class="heading" id="html">
<h2>HTML</h2>
</div>
<div class="section" id="html-syntax">
<div class="col">
<h3>Syntax</h3>
<ul>
<li>Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment.</li>
<li>Nested elements should be indented once (two spaces).</li>
<li>Always use double quotes, never single quotes, on attributes.</li>
<li>Don't include a trailing slash in self-closing elements—the <a href="http://dev.w3.org/html5/spec-author-view/syntax.html#syntax-start-tag">HTML5 spec</a> says they're optional.</li>
<li>Don’t omit optional closing tags (e.g. <code></li></code> or <code></body></code>).</li>
</ul>
</div>
<div class="col">
{% highlight html %}{% include html/syntax.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-doctype">
<div class="col">
<h3>HTML5 doctype</h3>
<p>Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.</p>
</div>
<div class="col">
{% highlight html %}{% include html/doctype.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-lang">
<div class="col">
<h3>Language attribute</h3>
<p>From the HTML5 spec:</p>
<blockquote>
<p>Authors are encouraged to specify a lang attribute on the root html element, giving the document's language. This aids speech synthesis tools to determine what pronunciations to use, translation tools to determine what rules to use, and so forth.</p>
</blockquote>
<p>Read more about the <code>lang</code> attribute <a href="http://www.w3.org/html/wg/drafts/html/master/semantics.html#the-html-element">in the spec</a>.</p>
<p>Head to Sitepoint for a <a href="http://reference.sitepoint.com/html/lang-codes">list of language codes</a>.</p>
</div>
<div class="col">
{% highlight html %}{% include html/lang.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-ie-compatibility-mode">
<div class="col">
<h3>IE compatibility mode</h3>
<p>Internet Explorer supports the use of a document compatibility <code><meta></code> tag to specify what version of IE the page should be rendered as. Unless circumstances require otherwise, it's most useful to instruct IE to use the latest supported mode with <strong>edge mode</strong>.</p>
<p>For more information, <a href="http://stackoverflow.com/questions/6771258/whats-the-difference-if-meta-http-equiv-x-ua-compatible-content-ie-edge-e">read this awesome Stack Overflow article</a>.</p>
</div>
<div class="col">
{% highlight html %}{% include html/ie-compatibility-mode.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-encoding">
<div class="col">
<h3>Character encoding</h3>
<p>Quickly and easily ensure proper rendering of your content by declaring an explicit character encoding. When doing so, you may avoid using character entities in your HTML, provided their encoding matches that of the document (generally UTF-8).</p>
</div>
<div class="col">
{% highlight html %}{% include html/encoding.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-style-script">
<div class="col">
<h3>CSS and JavaScript includes</h3>
<p>Per HTML5 spec, typically there is no need to specify a <code>type</code> when including CSS and JavaScript files as <code>text/css</code> and <code>text/javascript</code> are their respective defaults.</p>
<h4>HTML5 spec links</h4>
<ul>
<li><a href="http://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-link-element">Using link</a></li>
<li><a href="http://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-style-element">Using style</a></li>
<li><a href="http://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#the-script-element">Using script</a></li>
</ul>
</div>
<div class="col">
{% highlight html %}{% include html/style-script.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-practicality">
<div class="col">
<h3>Practicality over purity</h3>
<p>Strive to maintain HTML standards and semantics, but not at the expense of practicality. Use the least amount of markup with the fewest intricacies whenever possible.</p>
</div>
</div>
<div class="section" id="html-attribute-order">
<div class="col">
<h3>Attribute order</h3>
<p>HTML attributes should come in this particular order for easier reading of code.</p>
<ul>
<li><code>class</code></li>
<li><code>id</code>, <code>name</code></li>
<li><code>data-*</code></li>
<li><code>src</code>, <code>for</code>, <code>type</code>, <code>href</code>, <code>value</code></li>
<li><code>title</code>, <code>alt</code></li>
<li><code>aria-*</code>, <code>role</code></li>
</ul>
<p>Classes make for great reusable components, so they come first. Ids are more specific and should be used sparingly (e.g., for in-page bookmarks), so they come second.</p>
</div>
<div class="col">
{% highlight html %}{% include html/attribute-order.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-boolean-attributes">
<div class="col">
<h3>Boolean attributes</h3>
<p>A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement.</p>
<p>For further reading, consult the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#boolean-attributes">WhatWG section on boolean attributes</a>:</p>
<blockquote>
<p>The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.</p>
</blockquote>
<p>If you <em>must</em> include the attribute's value, and <strong>you don't need to</strong>, follow this WhatWG guideline:</p>
<blockquote>
<p>If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace.</p>
</blockquote>
<p><strong>In short, don't add a value.</strong></p>
</div>
<div class="col">
{% highlight html %}{% include html/boolean-attributes.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-reducing-markup">
<div class="col">
<h3>Reducing markup</h3>
<p>Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML. Take the following example:</p>
</div>
<div class="col">
{% highlight html %}{% include html/reducing-markup.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="html-javascript">
<div class="col">
<h3>JavaScript generated markup</h3>
<p>Writing markup in a JavaScript file makes the content harder to find, harder to edit, and less performant. Avoid it whenever possible.</p>
</div>
</div>
<div class="heading" id="css">
<h2>CSS</h2>
</div>
<div class="section" id="css-syntax">
<div class="col">
<h3>Syntax</h3>
<ul>
<li>Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment.</li>
<li>When grouping selectors, keep individual selectors to a single line.</li>
<li>Include one space before the opening brace of declaration blocks for legibility.</li>
<li>Place closing braces of declaration blocks on a new line.</li>
<li>Include one space after <code>:</code> for each declaration.</li>
<li>Each declaration should appear on its own line for more accurate error reporting.</li>
<li>End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it.</li>
<li>Comma-separated property values should include a space after each comma (e.g., <code>box-shadow</code>).</li>
<li>Don't include spaces after commas <em>within</em> <code>rgb()</code>, <code>rgba()</code>, <code>hsl()</code>, <code>hsla()</code>, or <code>rect()</code> values. This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space).</li>
<li>Don't prefix property values or color parameters with a leading zero (e.g., <code>.5</code> instead of <code>0.5</code> and <code>-.5px</code> instead of <code>-0.5px</code>).</li>
<li>Lowercase all hex values, e.g., <code>#fff</code>. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.</li>
<li>Use shorthand hex values where available, e.g., <code>#fff</code> instead of <code>#ffffff</code>.</li>
<li>Quote attribute values in selectors, e.g., <code>input[type="text"]</code>. <a href="http://mathiasbynens.be/notes/unquoted-attribute-values#css">They’re only optional in some cases</a>, and it’s a good practice for consistency.</li>
<li>Avoid specifying units for zero values, e.g., <code>margin: 0;</code> instead of <code>margin: 0px;</code>.</li>
</ul>
<p>Questions on the terms used here? See the <a href="http://en.wikipedia.org/wiki/Cascading_Style_Sheets#Syntax">syntax section of the Cascading Style Sheets article</a> on Wikipedia.</p>
</div>
<div class="col">
{% highlight css %}{% include css/syntax.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-declaration-order">
<div class="col">
<h3>Declaration order</h3>
<p>Related property declarations should be grouped together following the order:</p>
<ol>
<li>Positioning</li>
<li>Box model</li>
<li>Typographic</li>
<li>Visual</li>
</ol>
<p>Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.</p>
<p>Everything else takes place <em>inside</em> the component or without impacting the previous two sections, and thus they come last.</p>
<p>For a complete list of properties and their order, please see <a href="http://twitter.github.com/recess">Recess</a>.</p>
</div>
<div class="col">
{% highlight css %}{% include css/declaration-order.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-import">
<div class="col">
<h3>Don't use <code>@import</code></h3>
<p>Compared to <code><link></code>s, <code>@import</code> is slower, adds extra page requests, and can cause other unforeseen problems. Avoid them and instead opt for an alternate approach:</p>
<ul>
<li>Use multiple <code><link></code> elements</li>
<li>Compile your CSS with a preprocessor like Sass or Less into a single file</li>
<li>Concatenate your CSS files with features provided in Rails, Jekyll, and other environments</li>
</ul>
<p>For more information, <a href="http://www.stevesouders.com/blog/2009/04/09/dont-use-import/">read this article by Steve Souders</a>.</p>
</div>
<div class="col">
{% highlight html %}{% include css/import.html %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-media-queries">
<div class="col">
<h3>Media query placement</h3>
<p>Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.</p>
</div>
<div class="col">
{% highlight css %}{% include css/media-queries.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-prefixed-properties">
<div class="col">
<h3>Prefixed properties</h3>
<p>When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.</p>
<p>In Textmate, use <strong>Text → Edit Each Line in Selection</strong> (⌃⌘A). In Sublime Text 2, use <strong>Selection → Add Previous Line</strong> (⌃⇧↑) and <strong>Selection → Add Next Line</strong> (⌃⇧↓).</p>
</div>
<div class="col">
{% highlight css %}{% include css/prefixed-properties.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-single-declarations">
<div class="col">
<h3>Single declarations</h3>
<p>In instances where a rule set includes <strong>only one declaration</strong>, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.</p>
<p>The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.</p>
</div>
<div class="col">
{% highlight css %}{% include css/single-declarations.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-shorthand">
<div class="col">
<h3>Shorthand notation</h3>
<p>Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:</p>
<ul>
<li><code>padding</code></li>
<li><code>margin</code></li>
<li><code>font</code></li>
<li><code>background</code></li>
<li><code>border</code></li>
<li><code>border-radius</code></li>
</ul>
<p>Often times we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.</p>
<p>The Mozilla Developer Network has a great article on <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties">shorthand properties</a> for those unfamiliar with notation and behavior.</p>
</div>
<div class="col">
{% highlight css %}{% include css/shorthand.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-nesting">
<div class="col">
<h3>Nesting in Less and Sass</h3>
<p>Avoid unnecessary nesting. Just because you can nest, doesn't mean you always should. Consider nesting only if you must scope styles to a parent and if there are multiple elements to be nested.</p>
</div>
<div class="col">
{% highlight scss %}{% include css/nesting.scss %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-comments">
<div class="col">
<h3>Comments</h3>
<p>Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.</p>
<p>Be sure to write in complete sentences for larger comments and succinct phrases for general notes.</p>
</div>
<div class="col">
{% highlight css %}{% include css/comments.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-classes">
<div class="col">
<h3>Class names</h3>
<ul>
<li>Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g., <code>.btn</code> and <code>.btn-danger</code>).</li>
<li>Avoid excessive and arbitrary shorthand notation. <code>.btn</code> is useful for <em>button</em>, but <code>.s</code> doesn't mean anything.</li>
<li>Keep classes as short and succinct as possible.</li>
<li>Use meaningful names; use structural or purposeful names over presentational.</li>
<li>Prefix classes based on the closest parent or base class.</li>
<li>Use <code>.js-*</code> classes to denote behavior (as opposed to style), but keep these classes out of your CSS.</li>
</ul>
<p>It's also useful to apply many of these same rules when creating Sass and Less variable names.</p>
</div>
<div class="col">
{% highlight css %}{% include css/class-names.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-selectors">
<div class="col">
<h3>Selectors</h3>
<ul>
<li>Use classes over generic element tag for optimum rendering performance.</li>
<li>Avoid using several attribute selectors (e.g., <code>[class^="..."]</code>) on commonly occuring components. Browser performance is known to be impacted by these.</li>
<li>Keep selectors short and strive to limit the number of elements in each selector to three.</li>
<li>Scope classes to the closest parent <strong>only</strong> when necessary (e.g., when not using prefixed classes).</li>
</ul>
<p>Additional reading:</p>
<ul>
<li><a href="http://markdotto.com/2012/02/16/scope-css-classes-with-prefixes/">Scope CSS classes with prefixes</a></li>
<li><a href="http://markdotto.com/2012/03/02/stop-the-cascade/">Stop the cascade</a></li>
</ul>
</div>
<div class="col">
{% highlight css %}{% include css/selectors.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-organization">
<div class="col">
<h3>Organization</h3>
<ul>
<li>Organize sections of code by component.</li>
<li>Develop a consistent commenting hierarchy.</li>
<li>Use consistent white space to your advantage when separating sections of code for scanning larger documents.</li>
<li>When using multiple CSS files, break them down by component instead of page. Pages can be rearranged and components moved.</li>
</ul>
</div>
<div class="col">
{% highlight css %}{% include css/organization-comments.css %}{% endhighlight %}
</div>
</div>
<div class="section" id="css-editor-prefs">
<div class="col">
<h3>Editor preferences</h3>
<p>Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:</p>
<ul>
<li>Use soft-tabs set to two spaces.</li>
<li>Trim trailing white space on save.</li>
<li>Set encoding to UTF-8.</li>
<li>Add new line at end of files.</li>
</ul>
<p>Consider documenting and applying these preferences to your project's <code>.editorconfig</code> file. For an example, see <a href="https://github.com/twbs/bootstrap/blob/master/.editorconfig">the one in Bootstrap</a>. Learn more <a href="http://editorconfig.org">about EditorConfig</a>.</p>
</div>
</div>
| mit |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/gpu/command_buffer/service/gles2_cmd_copy_texture_chromium.cc | 22247 | // 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.
#include "gpu/command_buffer/service/gles2_cmd_copy_texture_chromium.h"
#include <algorithm>
#include "base/basictypes.h"
#include "gpu/command_buffer/service/gl_utils.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#define SHADER(src) \
"#ifdef GL_ES\n" \
"precision mediump float;\n" \
"#define TexCoordPrecision mediump\n" \
"#else\n" \
"#define TexCoordPrecision\n" \
"#endif\n" #src
#define SHADER_2D(src) \
"#define SamplerType sampler2D\n" \
"#define TextureLookup texture2D\n" SHADER(src)
#define SHADER_RECTANGLE_ARB(src) \
"#define SamplerType sampler2DRect\n" \
"#define TextureLookup texture2DRect\n" SHADER(src)
#define SHADER_EXTERNAL_OES(src) \
"#extension GL_OES_EGL_image_external : require\n" \
"#define SamplerType samplerExternalOES\n" \
"#define TextureLookup texture2D\n" SHADER(src)
#define FRAGMENT_SHADERS(src) \
SHADER_2D(src), SHADER_RECTANGLE_ARB(src), SHADER_EXTERNAL_OES(src)
namespace {
const GLfloat kIdentityMatrix[16] = {1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f};
enum VertexShaderId {
VERTEX_SHADER_COPY_TEXTURE,
VERTEX_SHADER_COPY_TEXTURE_FLIP_Y,
NUM_VERTEX_SHADERS,
};
enum FragmentShaderId {
FRAGMENT_SHADER_COPY_TEXTURE_2D,
FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES,
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_2D,
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_EXTERNAL_OES,
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_2D,
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_EXTERNAL_OES,
NUM_FRAGMENT_SHADERS,
};
const char* vertex_shader_source[NUM_VERTEX_SHADERS] = {
// VERTEX_SHADER_COPY_TEXTURE
SHADER(
uniform vec2 u_vertex_translate;
uniform vec2 u_half_size;
attribute vec4 a_position;
varying TexCoordPrecision vec2 v_uv;
void main(void) {
gl_Position = a_position + vec4(u_vertex_translate, 0.0, 0.0);
v_uv = a_position.xy * vec2(u_half_size.s, u_half_size.t) +
vec2(u_half_size.s, u_half_size.t);
}),
// VERTEX_SHADER_COPY_TEXTURE_FLIP_Y
SHADER(
uniform vec2 u_vertex_translate;
uniform vec2 u_half_size;
attribute vec4 a_position;
varying TexCoordPrecision vec2 v_uv;
void main(void) {
gl_Position = a_position + vec4(u_vertex_translate, 0.0, 0.0);
v_uv = a_position.xy * vec2(u_half_size.s, -u_half_size.t) +
vec2(u_half_size.s, u_half_size.t);
}),
};
const char* fragment_shader_source[NUM_FRAGMENT_SHADERS] = {
// FRAGMENT_SHADER_COPY_TEXTURE_*
FRAGMENT_SHADERS(
uniform SamplerType u_sampler;
uniform mat4 u_tex_coord_transform;
varying TexCoordPrecision vec2 v_uv;
void main(void) {
TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1);
gl_FragColor = TextureLookup(u_sampler, uv.st);
}),
// FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_*
FRAGMENT_SHADERS(
uniform SamplerType u_sampler;
uniform mat4 u_tex_coord_transform;
varying TexCoordPrecision vec2 v_uv;
void main(void) {
TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1);
gl_FragColor = TextureLookup(u_sampler, uv.st);
gl_FragColor.rgb *= gl_FragColor.a;
}),
// FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_*
FRAGMENT_SHADERS(
uniform SamplerType u_sampler;
uniform mat4 u_tex_coord_transform;
varying TexCoordPrecision vec2 v_uv;
void main(void) {
TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1);
gl_FragColor = TextureLookup(u_sampler, uv.st);
if (gl_FragColor.a > 0.0)
gl_FragColor.rgb /= gl_FragColor.a;
}),
};
// Returns the correct vertex shader id to evaluate the copy operation for
// the CHROMIUM_flipy setting.
VertexShaderId GetVertexShaderId(bool flip_y) {
// bit 0: flip y
static VertexShaderId shader_ids[] = {
VERTEX_SHADER_COPY_TEXTURE,
VERTEX_SHADER_COPY_TEXTURE_FLIP_Y,
};
unsigned index = flip_y ? 1 : 0;
return shader_ids[index];
}
// Returns the correct fragment shader id to evaluate the copy operation for
// the premultiply alpha pixel store settings and target.
FragmentShaderId GetFragmentShaderId(bool premultiply_alpha,
bool unpremultiply_alpha,
GLenum target) {
enum {
SAMPLER_2D,
SAMPLER_RECTANGLE_ARB,
SAMPLER_EXTERNAL_OES,
NUM_SAMPLERS
};
// bit 0: premultiply alpha
// bit 1: unpremultiply alpha
static FragmentShaderId shader_ids[][NUM_SAMPLERS] = {
{
FRAGMENT_SHADER_COPY_TEXTURE_2D,
FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES,
},
{
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_2D,
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_EXTERNAL_OES,
},
{
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_2D,
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_EXTERNAL_OES,
},
{
FRAGMENT_SHADER_COPY_TEXTURE_2D,
FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB,
FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES,
}};
unsigned index = (premultiply_alpha ? (1 << 0) : 0) |
(unpremultiply_alpha ? (1 << 1) : 0);
switch (target) {
case GL_TEXTURE_2D:
return shader_ids[index][SAMPLER_2D];
case GL_TEXTURE_RECTANGLE_ARB:
return shader_ids[index][SAMPLER_RECTANGLE_ARB];
case GL_TEXTURE_EXTERNAL_OES:
return shader_ids[index][SAMPLER_EXTERNAL_OES];
default:
break;
}
NOTREACHED();
return shader_ids[0][SAMPLER_2D];
}
void CompileShader(GLuint shader, const char* shader_source) {
glShaderSource(shader, 1, &shader_source, 0);
glCompileShader(shader);
#ifndef NDEBUG
GLint compile_status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status);
if (GL_TRUE != compile_status)
DLOG(ERROR) << "CopyTextureCHROMIUM: shader compilation failure.";
#endif
}
void DeleteShader(GLuint shader) {
if (shader)
glDeleteShader(shader);
}
bool BindFramebufferTexture2D(GLenum target,
GLuint texture_id,
GLuint framebuffer) {
DCHECK(target == GL_TEXTURE_2D || target == GL_TEXTURE_RECTANGLE_ARB);
glActiveTexture(GL_TEXTURE0);
glBindTexture(target, texture_id);
// NVidia drivers require texture settings to be a certain way
// or they won't report FRAMEBUFFER_COMPLETE.
glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target,
texture_id, 0);
#ifndef NDEBUG
GLenum fb_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
if (GL_FRAMEBUFFER_COMPLETE != fb_status) {
DLOG(ERROR) << "CopyTextureCHROMIUM: Incomplete framebuffer.";
return false;
}
#endif
return true;
}
void DoCopyTexImage2D(const gpu::gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLuint dest_id,
GLenum dest_internal_format,
GLsizei width,
GLsizei height,
GLuint framebuffer) {
DCHECK(source_target == GL_TEXTURE_2D ||
source_target == GL_TEXTURE_RECTANGLE_ARB);
if (BindFramebufferTexture2D(source_target, source_id, framebuffer)) {
glBindTexture(GL_TEXTURE_2D, dest_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glCopyTexImage2D(GL_TEXTURE_2D, 0 /* level */, dest_internal_format,
0 /* x */, 0 /* y */, width, height, 0 /* border */);
}
decoder->RestoreTextureState(source_id);
decoder->RestoreTextureState(dest_id);
decoder->RestoreTextureUnitBindings(0);
decoder->RestoreActiveTexture();
decoder->RestoreFramebufferBindings();
}
void DoCopyTexSubImage2D(const gpu::gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLuint dest_id,
GLint xoffset,
GLint yoffset,
GLint source_x,
GLint source_y,
GLsizei source_width,
GLsizei source_height,
GLuint framebuffer) {
DCHECK(source_target == GL_TEXTURE_2D ||
source_target == GL_TEXTURE_RECTANGLE_ARB);
if (BindFramebufferTexture2D(source_target, source_id, framebuffer)) {
glBindTexture(GL_TEXTURE_2D, dest_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0 /* level */, xoffset, yoffset,
source_x, source_y, source_width, source_height);
}
decoder->RestoreTextureState(source_id);
decoder->RestoreTextureState(dest_id);
decoder->RestoreTextureUnitBindings(0);
decoder->RestoreActiveTexture();
decoder->RestoreFramebufferBindings();
}
} // namespace
namespace gpu {
CopyTextureCHROMIUMResourceManager::CopyTextureCHROMIUMResourceManager()
: initialized_(false),
vertex_shaders_(NUM_VERTEX_SHADERS, 0u),
fragment_shaders_(NUM_FRAGMENT_SHADERS, 0u),
buffer_id_(0u),
framebuffer_(0u) {}
CopyTextureCHROMIUMResourceManager::~CopyTextureCHROMIUMResourceManager() {
// |buffer_id_| and |framebuffer_| can be not-null because when GPU context is
// lost, this class can be deleted without releasing resources like
// GLES2DecoderImpl.
}
void CopyTextureCHROMIUMResourceManager::Initialize(
const gles2::GLES2Decoder* decoder) {
static_assert(
kVertexPositionAttrib == 0u,
"kVertexPositionAttrib must be 0");
DCHECK(!buffer_id_);
DCHECK(!framebuffer_);
DCHECK(programs_.empty());
// Initialize all of the GPU resources required to perform the copy.
glGenBuffersARB(1, &buffer_id_);
glBindBuffer(GL_ARRAY_BUFFER, buffer_id_);
const GLfloat kQuadVertices[] = {-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f};
glBufferData(
GL_ARRAY_BUFFER, sizeof(kQuadVertices), kQuadVertices, GL_STATIC_DRAW);
glGenFramebuffersEXT(1, &framebuffer_);
decoder->RestoreBufferBindings();
initialized_ = true;
}
void CopyTextureCHROMIUMResourceManager::Destroy() {
if (!initialized_)
return;
glDeleteFramebuffersEXT(1, &framebuffer_);
framebuffer_ = 0;
std::for_each(vertex_shaders_.begin(), vertex_shaders_.end(), DeleteShader);
std::for_each(
fragment_shaders_.begin(), fragment_shaders_.end(), DeleteShader);
for (ProgramMap::const_iterator it = programs_.begin(); it != programs_.end();
++it) {
const ProgramInfo& info = it->second;
glDeleteProgram(info.program);
}
glDeleteBuffersARB(1, &buffer_id_);
buffer_id_ = 0;
}
void CopyTextureCHROMIUMResourceManager::DoCopyTexture(
const gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLenum source_internal_format,
GLuint dest_id,
GLenum dest_internal_format,
GLsizei width,
GLsizei height,
bool flip_y,
bool premultiply_alpha,
bool unpremultiply_alpha) {
bool premultiply_alpha_change = premultiply_alpha ^ unpremultiply_alpha;
// GL_INVALID_OPERATION is generated if the currently bound framebuffer's
// format does not contain a superset of the components required by the base
// format of internalformat.
// https://www.khronos.org/opengles/sdk/docs/man/xhtml/glCopyTexImage2D.xml
bool source_format_contain_superset_of_dest_format =
(source_internal_format == dest_internal_format &&
source_internal_format != GL_BGRA_EXT) ||
(source_internal_format == GL_RGBA && dest_internal_format == GL_RGB);
// GL_TEXTURE_RECTANGLE_ARB on FBO is supported by OpenGL, not GLES2,
// so restrict this to GL_TEXTURE_2D.
if (source_target == GL_TEXTURE_2D && !flip_y && !premultiply_alpha_change &&
source_format_contain_superset_of_dest_format) {
DoCopyTexImage2D(decoder,
source_target,
source_id,
dest_id,
dest_internal_format,
width,
height,
framebuffer_);
return;
}
// Use kIdentityMatrix if no transform passed in.
DoCopyTextureWithTransform(decoder, source_target, source_id, dest_id, width,
height, flip_y, premultiply_alpha,
unpremultiply_alpha, kIdentityMatrix);
}
void CopyTextureCHROMIUMResourceManager::DoCopySubTexture(
const gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLenum source_internal_format,
GLuint dest_id,
GLenum dest_internal_format,
GLint xoffset,
GLint yoffset,
GLint x,
GLint y,
GLsizei width,
GLsizei height,
GLsizei dest_width,
GLsizei dest_height,
GLsizei source_width,
GLsizei source_height,
bool flip_y,
bool premultiply_alpha,
bool unpremultiply_alpha) {
bool premultiply_alpha_change = premultiply_alpha ^ unpremultiply_alpha;
// GL_INVALID_OPERATION is generated if the currently bound framebuffer's
// format does not contain a superset of the components required by the base
// format of internalformat.
// https://www.khronos.org/opengles/sdk/docs/man/xhtml/glCopyTexImage2D.xml
bool source_format_contain_superset_of_dest_format =
(source_internal_format == dest_internal_format &&
source_internal_format != GL_BGRA_EXT) ||
(source_internal_format == GL_RGBA && dest_internal_format == GL_RGB);
// GL_TEXTURE_RECTANGLE_ARB on FBO is supported by OpenGL, not GLES2,
// so restrict this to GL_TEXTURE_2D.
if (source_target == GL_TEXTURE_2D && !flip_y && !premultiply_alpha_change &&
source_format_contain_superset_of_dest_format) {
DoCopyTexSubImage2D(decoder, source_target, source_id, dest_id, xoffset,
yoffset, x, y, width, height, framebuffer_);
return;
}
DoCopyTextureInternal(decoder, source_target, source_id, dest_id, xoffset,
yoffset, x, y, width, height, dest_width, dest_height,
source_width, source_height, flip_y, premultiply_alpha,
unpremultiply_alpha, kIdentityMatrix);
}
void CopyTextureCHROMIUMResourceManager::DoCopyTextureWithTransform(
const gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLuint dest_id,
GLsizei width,
GLsizei height,
bool flip_y,
bool premultiply_alpha,
bool unpremultiply_alpha,
const GLfloat transform_matrix[16]) {
GLsizei dest_width = width;
GLsizei dest_height = height;
DoCopyTextureInternal(decoder, source_target, source_id, dest_id, 0, 0, 0, 0,
width, height, dest_width, dest_height, width, height,
flip_y, premultiply_alpha, unpremultiply_alpha,
transform_matrix);
}
void CopyTextureCHROMIUMResourceManager::DoCopyTextureInternal(
const gles2::GLES2Decoder* decoder,
GLenum source_target,
GLuint source_id,
GLuint dest_id,
GLint xoffset,
GLint yoffset,
GLint x,
GLint y,
GLsizei width,
GLsizei height,
GLsizei dest_width,
GLsizei dest_height,
GLsizei source_width,
GLsizei source_height,
bool flip_y,
bool premultiply_alpha,
bool unpremultiply_alpha,
const GLfloat transform_matrix[16]) {
DCHECK(source_target == GL_TEXTURE_2D ||
source_target == GL_TEXTURE_RECTANGLE_ARB ||
source_target == GL_TEXTURE_EXTERNAL_OES);
DCHECK_GE(xoffset, 0);
DCHECK_LE(xoffset + width, dest_width);
DCHECK_GE(yoffset, 0);
DCHECK_LE(yoffset + height, dest_height);
if (!initialized_) {
DLOG(ERROR) << "CopyTextureCHROMIUM: Uninitialized manager.";
return;
}
VertexShaderId vertex_shader_id = GetVertexShaderId(flip_y);
DCHECK_LT(static_cast<size_t>(vertex_shader_id), vertex_shaders_.size());
FragmentShaderId fragment_shader_id = GetFragmentShaderId(
premultiply_alpha, unpremultiply_alpha, source_target);
DCHECK_LT(static_cast<size_t>(fragment_shader_id), fragment_shaders_.size());
ProgramMapKey key(vertex_shader_id, fragment_shader_id);
ProgramInfo* info = &programs_[key];
// Create program if necessary.
if (!info->program) {
info->program = glCreateProgram();
GLuint* vertex_shader = &vertex_shaders_[vertex_shader_id];
if (!*vertex_shader) {
*vertex_shader = glCreateShader(GL_VERTEX_SHADER);
CompileShader(*vertex_shader, vertex_shader_source[vertex_shader_id]);
}
glAttachShader(info->program, *vertex_shader);
GLuint* fragment_shader = &fragment_shaders_[fragment_shader_id];
if (!*fragment_shader) {
*fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
CompileShader(*fragment_shader,
fragment_shader_source[fragment_shader_id]);
}
glAttachShader(info->program, *fragment_shader);
glBindAttribLocation(info->program, kVertexPositionAttrib, "a_position");
glLinkProgram(info->program);
#ifndef NDEBUG
GLint linked;
glGetProgramiv(info->program, GL_LINK_STATUS, &linked);
if (!linked)
DLOG(ERROR) << "CopyTextureCHROMIUM: program link failure.";
#endif
info->vertex_translate_handle = glGetUniformLocation(info->program,
"u_vertex_translate");
info->tex_coord_transform_handle =
glGetUniformLocation(info->program, "u_tex_coord_transform");
info->half_size_handle = glGetUniformLocation(info->program, "u_half_size");
info->sampler_handle = glGetUniformLocation(info->program, "u_sampler");
}
glUseProgram(info->program);
glUniformMatrix4fv(info->tex_coord_transform_handle, 1, GL_FALSE,
transform_matrix);
GLint x_translate = xoffset - x;
GLint y_translate = yoffset - y;
if (!x_translate && !y_translate) {
glUniform2f(info->vertex_translate_handle, 0.0f, 0.0f);
} else {
// transform offsets from ([0, dest_width], [0, dest_height]) coord.
// to ([-1, 1], [-1, 1]) coord.
GLfloat x_translate_on_vertex = ((2.f * x_translate) / dest_width);
GLfloat y_translate_on_vertex = ((2.f * y_translate) / dest_height);
// Pass translation to the shader program.
glUniform2f(info->vertex_translate_handle, x_translate_on_vertex,
y_translate_on_vertex);
}
if (source_target == GL_TEXTURE_RECTANGLE_ARB)
glUniform2f(info->half_size_handle, source_width / 2.0f,
source_height / 2.0f);
else
glUniform2f(info->half_size_handle, 0.5f, 0.5f);
if (BindFramebufferTexture2D(GL_TEXTURE_2D, dest_id, framebuffer_)) {
#ifndef NDEBUG
// glValidateProgram of MACOSX validates FBO unlike other platforms, so
// glValidateProgram must be called after FBO binding. crbug.com/463439
glValidateProgram(info->program);
GLint validation_status;
glGetProgramiv(info->program, GL_VALIDATE_STATUS, &validation_status);
if (GL_TRUE != validation_status) {
DLOG(ERROR) << "CopyTextureCHROMIUM: Invalid shader.";
return;
}
#endif
decoder->ClearAllAttributes();
glEnableVertexAttribArray(kVertexPositionAttrib);
glBindBuffer(GL_ARRAY_BUFFER, buffer_id_);
glVertexAttribPointer(kVertexPositionAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
glUniform1i(info->sampler_handle, 0);
glBindTexture(source_target, source_id);
glTexParameterf(source_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(source_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(source_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(source_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_FALSE);
glDisable(GL_BLEND);
bool need_scissor =
xoffset || yoffset || width != dest_width || height != dest_height;
if (need_scissor) {
glEnable(GL_SCISSOR_TEST);
glScissor(xoffset, yoffset, width, height);
} else {
glDisable(GL_SCISSOR_TEST);
}
glViewport(0, 0, dest_width, dest_height);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
decoder->RestoreAllAttributes();
decoder->RestoreTextureState(source_id);
decoder->RestoreTextureState(dest_id);
decoder->RestoreTextureUnitBindings(0);
decoder->RestoreActiveTexture();
decoder->RestoreProgramBindings();
decoder->RestoreBufferBindings();
decoder->RestoreFramebufferBindings();
decoder->RestoreGlobalState();
}
} // namespace gpu
| mit |
jianghaolu/azure-sdk-for-java | azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/PageImpl.java | 1747 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.resources.implementation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.azure.Page;
import java.util.List;
/**
* An instance of this class defines a page of Azure resources and a link to
* get the next page of resources, if any.
*
* @param <T> type of Azure resource
*/
public class PageImpl<T> implements Page<T> {
/**
* The link to the next page.
*/
@JsonProperty("nextLink")
private String nextPageLink;
/**
* The list of items.
*/
@JsonProperty("value")
private List<T> items;
/**
* Gets the link to the next page.
*
* @return the link to the next page.
*/
@Override
public String nextPageLink() {
return this.nextPageLink;
}
/**
* Gets the list of items.
*
* @return the list of items in {@link List}.
*/
@Override
public List<T> items() {
return items;
}
/**
* Sets the link to the next page.
*
* @param nextPageLink the link to the next page.
* @return this Page object itself.
*/
public PageImpl<T> setNextPageLink(String nextPageLink) {
this.nextPageLink = nextPageLink;
return this;
}
/**
* Sets the list of items.
*
* @param items the list of items in {@link List}.
* @return this Page object itself.
*/
public PageImpl<T> setItems(List<T> items) {
this.items = items;
return this;
}
}
| mit |
toyodundy/shirasagi | db/seeds/childcare/layouts/general.layout.html | 1049 | <html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=yes,minimum-scale=1.0,maximum-scale=2.0">
<link href="/css/style.css" media="all" rel="stylesheet" />
<script src="/js/common.js"></script>
<script src="/js/flexibility.js"></script>
<script src="/js/heightLine.js"></script>
<!--[if lt IE 9]>
<script src="/js/selectivizr.js"></script>
<script src="/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div id="page">
{{ part "tool" }}
{{ part "head" }}
{{ part "navi" }}
<div id="wrap">
{{ part "breadcrumbs" }}
<div id="main">
<section id="yield" class="content-page">
<header id="page-title"><h1>#{page_name}</h1></header>
{{ yield }}
{{ part "sns" }}
</section>
</div>
<div id="side">
{{ part "purpose/birth/folder" }}
{{ part "age/zero/folder" }}
{{ part "sub-menu/banner" }}
</div>
</div>
{{ part "pagetop" }}
{{ part "foot" }}
</div>
</body>
</html>
| mit |
thekordy/ticketit | src/Views/bootstrap3/admin/category/edit.blade.php | 781 | @extends($master)
@section('page', trans('ticketit::admin.category-edit-title', ['name' => ucwords($category->name)]))
@section('content')
@include('ticketit::shared.header')
<div class="well bs-component">
{!! CollectiveForm::model($category, [
'route' => [$setting->grab('admin_route').'.category.update', $category->id],
'method' => 'PATCH',
'class' => 'form-horizontal'
]) !!}
<legend>{{ trans('ticketit::admin.category-edit-title', ['name' => ucwords($category->name)]) }}</legend>
@include('ticketit::admin.category.form', ['update', true])
{!! CollectiveForm::close() !!}
</div>
@stop
| mit |
hansbonini/cloud9-magento | www/app/code/core/Mage/Api2/Model/Request/Interpreter.php | 2436 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Api2
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Request content interpreter factory
*
* @category Mage
* @package Mage_Api2
* @author Magento Core Team <[email protected]>
*/
abstract class Mage_Api2_Model_Request_Interpreter
{
/**
* Request body interpreters factory
*
* @param string $type
* @return Mage_Api2_Model_Request_Interpreter_Interface
* @throws Exception|Mage_Api2_Exception
*/
public static function factory($type)
{
/** @var $helper Mage_Api2_Helper_Data */
$helper = Mage::helper('api2/data');
$adapters = $helper->getRequestInterpreterAdapters();
if (empty($adapters) || !is_array($adapters)) {
throw new Exception('Request interpreter adapters is not set.');
}
$adapterModel = null;
foreach ($adapters as $item) {
$itemType = $item->type;
if ($itemType == $type) {
$adapterModel = $item->model;
break;
}
}
if ($adapterModel === null) {
throw new Mage_Api2_Exception(
sprintf('Server can not understand Content-Type HTTP header media type "%s"', $type),
Mage_Api2_Model_Server::HTTP_BAD_REQUEST
);
}
$adapter = Mage::getModel($adapterModel);
if (!$adapter) {
throw new Exception(sprintf('Request interpreter adapter "%s" not found.', $type));
}
return $adapter;
}
}
| mit |
wakanpaladin/mybackbone | test/collection.js | 35957 | $(document).ready(function() {
var a, b, c, d, e, col, otherCol;
module("Backbone.Collection", {
setup: function() {
a = new Backbone.Model({id: 3, label: 'a'});
b = new Backbone.Model({id: 2, label: 'b'});
c = new Backbone.Model({id: 1, label: 'c'});
d = new Backbone.Model({id: 0, label: 'd'});
e = null;
col = new Backbone.Collection([a,b,c,d]);
otherCol = new Backbone.Collection();
}
});
test("new and sort", 9, function() {
var counter = 0;
col.on('sort', function(){ counter++; });
equal(col.first(), a, "a should be first");
equal(col.last(), d, "d should be last");
col.comparator = function(a, b) {
return a.id > b.id ? -1 : 1;
};
col.sort();
equal(counter, 1);
equal(col.first(), a, "a should be first");
equal(col.last(), d, "d should be last");
col.comparator = function(model) { return model.id; };
col.sort();
equal(counter, 2);
equal(col.first(), d, "d should be first");
equal(col.last(), a, "a should be last");
equal(col.length, 4);
});
test("String comparator.", 1, function() {
var collection = new Backbone.Collection([
{id: 3},
{id: 1},
{id: 2}
], {comparator: 'id'});
deepEqual(collection.pluck('id'), [1, 2, 3]);
});
test("new and parse", 3, function() {
var Collection = Backbone.Collection.extend({
parse : function(data) {
return _.filter(data, function(datum) {
return datum.a % 2 === 0;
});
}
});
var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
var collection = new Collection(models, {parse: true});
strictEqual(collection.length, 2);
strictEqual(collection.first().get('a'), 2);
strictEqual(collection.last().get('a'), 4);
});
test("get", 6, function() {
equal(col.get(0), d);
equal(col.get(d.clone()), d);
equal(col.get(2), b);
equal(col.get({id: 1}), c);
equal(col.get(c.clone()), c);
equal(col.get(col.first().cid), col.first());
});
test("get with non-default ids", 5, function() {
var col = new Backbone.Collection();
var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
var model = new MongoModel({_id: 100});
col.add(model);
equal(col.get(100), model);
equal(col.get(model.cid), model);
equal(col.get(model), model);
equal(col.get(101), void 0);
var col2 = new Backbone.Collection();
col2.model = MongoModel;
col2.add(model.attributes);
equal(col2.get(model.clone()), col2.first());
});
test("update index when id changes", 4, function() {
var col = new Backbone.Collection();
col.add([
{id : 0, name : 'one'},
{id : 1, name : 'two'}
]);
var one = col.get(0);
equal(one.get('name'), 'one');
col.on('change:name', function (model) { ok(this.get(model)); });
one.set({name: 'dalmatians', id : 101});
equal(col.get(0), null);
equal(col.get(101).get('name'), 'dalmatians');
});
test("at", 1, function() {
equal(col.at(2), c);
});
test("pluck", 1, function() {
equal(col.pluck('label').join(' '), 'a b c d');
});
test("add", 10, function() {
var added, opts, secondAdded;
added = opts = secondAdded = null;
e = new Backbone.Model({id: 10, label : 'e'});
otherCol.add(e);
otherCol.on('add', function() {
secondAdded = true;
});
col.on('add', function(model, collection, options){
added = model.get('label');
opts = options;
});
col.add(e, {amazing: true});
equal(added, 'e');
equal(col.length, 5);
equal(col.last(), e);
equal(otherCol.length, 1);
equal(secondAdded, null);
ok(opts.amazing);
var f = new Backbone.Model({id: 20, label : 'f'});
var g = new Backbone.Model({id: 21, label : 'g'});
var h = new Backbone.Model({id: 22, label : 'h'});
var atCol = new Backbone.Collection([f, g, h]);
equal(atCol.length, 3);
atCol.add(e, {at: 1});
equal(atCol.length, 4);
equal(atCol.at(1), e);
equal(atCol.last(), h);
});
test("add multiple models", 6, function() {
var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
for (var i = 0; i <= 5; i++) {
equal(col.at(i).get('at'), i);
}
});
test("add; at should have preference over comparator", 1, function() {
var Col = Backbone.Collection.extend({
comparator: function(a,b) {
return a.id > b.id ? -1 : 1;
}
});
var col = new Col([{id: 2}, {id: 3}]);
col.add(new Backbone.Model({id: 1}), {at: 1});
equal(col.pluck('id').join(' '), '3 1 2');
});
test("can't add model to collection twice", function() {
var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
equal(col.pluck('id').join(' '), '1 2 3');
});
test("can't add different model with same id to collection twice", 1, function() {
var col = new Backbone.Collection;
col.unshift({id: 101});
col.add({id: 101});
equal(col.length, 1);
});
test("merge in duplicate models with {merge: true}", 3, function() {
var col = new Backbone.Collection;
col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
col.add({id: 1, name: 'Moses'});
equal(col.first().get('name'), 'Moe');
col.add({id: 1, name: 'Moses'}, {merge: true});
equal(col.first().get('name'), 'Moses');
col.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
equal(col.first().get('name'), 'Tim');
});
test("add model to multiple collections", 10, function() {
var counter = 0;
var e = new Backbone.Model({id: 10, label : 'e'});
e.on('add', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colF);
} else {
equal(collection, colE);
}
});
var colE = new Backbone.Collection([]);
colE.on('add', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([]);
colF.on('add', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
colE.add(e);
equal(e.collection, colE);
colF.add(e);
equal(e.collection, colE);
});
test("add model with parse", 1, function() {
var Model = Backbone.Model.extend({
parse: function(obj) {
obj.value += 1;
return obj;
}
});
var Col = Backbone.Collection.extend({model: Model});
var col = new Col;
col.add({value: 1}, {parse: true});
equal(col.at(0).get('value'), 2);
});
test("add with parse and merge", function() {
var Model = Backbone.Model.extend({
parse: function (data) {
return data.model;
}
});
var collection = new Backbone.Collection();
collection.model = Model;
collection.add({id: 1});
collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
equal(collection.first().get('name'), 'Alf');
});
test("add model to collection with sort()-style comparator", 3, function() {
var col = new Backbone.Collection;
col.comparator = function(a, b) {
return a.get('name') < b.get('name') ? -1 : 1;
};
var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});
col.add(tom);
col.add(rob);
col.add(tim);
equal(col.indexOf(rob), 0);
equal(col.indexOf(tim), 1);
equal(col.indexOf(tom), 2);
});
test("comparator that depends on `this`", 2, function() {
var col = new Backbone.Collection;
col.negative = function(num) {
return -num;
};
col.comparator = function(a) {
return this.negative(a.id);
};
col.add([{id: 1}, {id: 2}, {id: 3}]);
deepEqual(col.pluck('id'), [3, 2, 1]);
col.comparator = function(a, b) {
return this.negative(b.id) - this.negative(a.id);
};
col.sort();
deepEqual(col.pluck('id'), [1, 2, 3]);
});
test("remove", 5, function() {
var removed = null;
var otherRemoved = null;
col.on('remove', function(model, col, options) {
removed = model.get('label');
equal(options.index, 3);
});
otherCol.on('remove', function(model, col, options) {
otherRemoved = true;
});
col.remove(d);
equal(removed, 'd');
equal(col.length, 3);
equal(col.first(), a);
equal(otherRemoved, null);
});
test("shift and pop", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
equal(col.shift().get('a'), 'a');
equal(col.pop().get('c'), 'c');
});
test("slice", 2, function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
var array = col.slice(1, 3);
equal(array.length, 2);
equal(array[0].get('b'), 'b');
});
test("events are unbound on remove", 3, function() {
var counter = 0;
var dj = new Backbone.Model();
var emcees = new Backbone.Collection([dj]);
emcees.on('change', function(){ counter++; });
dj.set({name : 'Kool'});
equal(counter, 1);
emcees.reset([]);
equal(dj.collection, undefined);
dj.set({name : 'Shadow'});
equal(counter, 1);
});
test("remove in multiple collections", 7, function() {
var modelData = {
id : 5,
title : 'Othello'
};
var passed = false;
var e = new Backbone.Model(modelData);
var f = new Backbone.Model(modelData);
f.on('remove', function() {
passed = true;
});
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([f]);
ok(e != f);
ok(colE.length === 1);
ok(colF.length === 1);
colE.remove(e);
equal(passed, false);
ok(colE.length === 0);
colF.remove(e);
ok(colF.length === 0);
equal(passed, true);
});
test("remove same model in multiple collection", 16, function() {
var counter = 0;
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.on('remove', function(model, collection) {
counter++;
equal(e, model);
if (counter > 1) {
equal(collection, colE);
} else {
equal(collection, colF);
}
});
var colE = new Backbone.Collection([e]);
colE.on('remove', function(model, collection) {
equal(e, model);
equal(colE, collection);
});
var colF = new Backbone.Collection([e]);
colF.on('remove', function(model, collection) {
equal(e, model);
equal(colF, collection);
});
equal(colE, e.collection);
colF.remove(e);
ok(colF.length === 0);
ok(colE.length === 1);
equal(counter, 1);
equal(colE, e.collection);
colE.remove(e);
equal(null, e.collection);
ok(colE.length === 0);
equal(counter, 2);
});
test("model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({id: 5, title: 'Othello'});
e.sync = function(method, model, options) { options.success(); };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("Colllection: non-persisted model destroy removes from all collections", 3, function() {
var e = new Backbone.Model({title: 'Othello'});
e.sync = function(method, model, options) { throw "should not be called"; };
var colE = new Backbone.Collection([e]);
var colF = new Backbone.Collection([e]);
e.destroy();
ok(colE.length === 0);
ok(colF.length === 0);
equal(undefined, e.collection);
});
test("fetch", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
collection.fetch();
equal(this.syncArgs.method, 'read');
equal(this.syncArgs.model, collection);
equal(this.syncArgs.options.parse, true);
collection.fetch({parse: false});
equal(this.syncArgs.options.parse, false);
});
test("fetch with an error response triggers an error event", 1, function () {
var collection = new Backbone.Collection();
collection.on('error', function () {
ok(true);
});
collection.sync = function (method, model, options) { options.error(); };
collection.fetch();
});
test("ensure fetch only parses once", 1, function() {
var collection = new Backbone.Collection;
var counter = 0;
collection.parse = function(models) {
counter++;
return models;
};
collection.url = '/test';
collection.fetch();
this.syncArgs.options.success();
equal(counter, 1);
});
test("create", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var model = collection.create({label: 'f'}, {wait: true});
equal(this.syncArgs.method, 'create');
equal(this.syncArgs.model, model);
equal(model.get('label'), 'f');
equal(model.collection, collection);
});
test("create with validate:true enforces validation", 2, function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
col.on('invalid', function (collection, attrs, options) {
equal(options.validationError, 'fail');
});
equal(col.create({"foo":"bar"}, {validate:true}), false);
});
test("a failing create returns model with errors", function() {
var ValidatingModel = Backbone.Model.extend({
validate: function(attrs) {
return "fail";
}
});
var ValidatingCollection = Backbone.Collection.extend({
model: ValidatingModel
});
var col = new ValidatingCollection();
var m = col.create({"foo":"bar"});
equal(m.validationError, 'fail');
equal(col.length, 1);
});
test("initialize", 1, function() {
var Collection = Backbone.Collection.extend({
initialize: function() {
this.one = 1;
}
});
var coll = new Collection;
equal(coll.one, 1);
});
test("toJSON", 1, function() {
equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
});
test("where and findWhere", 8, function() {
var model = new Backbone.Model({a: 1});
var coll = new Backbone.Collection([
model,
{a: 1},
{a: 1, b: 2},
{a: 2, b: 2},
{a: 3}
]);
equal(coll.where({a: 1}).length, 3);
equal(coll.where({a: 2}).length, 1);
equal(coll.where({a: 3}).length, 1);
equal(coll.where({b: 1}).length, 0);
equal(coll.where({b: 2}).length, 2);
equal(coll.where({a: 1, b: 2}).length, 1);
equal(coll.findWhere({a: 1}), model);
equal(coll.findWhere({a: 4}), void 0);
});
test("Underscore methods", 14, function() {
equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
equal(col.any(function(model){ return model.id === 100; }), false);
equal(col.any(function(model){ return model.id === 0; }), true);
equal(col.indexOf(b), 1);
equal(col.size(), 4);
equal(col.rest().length, 3);
ok(!_.include(col.rest(), a));
ok(_.include(col.rest(), d));
ok(!col.isEmpty());
ok(!_.include(col.without(d), d));
equal(col.max(function(model){ return model.id; }).id, 3);
equal(col.min(function(model){ return model.id; }).id, 0);
deepEqual(col.chain()
.filter(function(o){ return o.id % 2 === 0; })
.map(function(o){ return o.id * 2; })
.value(),
[4, 0]);
deepEqual(col.difference([c, d]), [a, b]);
});
test("sortedIndex", function () {
var model = new Backbone.Model({key: 2});
var collection = new (Backbone.Collection.extend({
comparator: 'key'
}))([model, {key: 1}]);
equal(collection.sortedIndex(model), 1);
equal(collection.sortedIndex(model, 'key'), 1);
equal(collection.sortedIndex(model, function (model) {
return model.get('key');
}), 1);
});
test("reset", 12, function() {
var resetCount = 0;
var models = col.models;
col.on('reset', function() { resetCount += 1; });
col.reset([]);
equal(resetCount, 1);
equal(col.length, 0);
equal(col.last(), null);
col.reset(models);
equal(resetCount, 2);
equal(col.length, 4);
equal(col.last(), d);
col.reset(_.map(models, function(m){ return m.attributes; }));
equal(resetCount, 3);
equal(col.length, 4);
ok(col.last() !== d);
ok(_.isEqual(col.last().attributes, d.attributes));
col.reset();
equal(col.length, 0);
equal(resetCount, 4);
});
test ("reset with different values", function(){
var col = new Backbone.Collection({id: 1});
col.reset({id: 1, a: 1});
equal(col.get(1).get('a'), 1);
});
test("same references in reset", function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection({id: 1});
collection.reset(model);
equal(collection.get(1), model);
});
test("reset passes caller options", 3, function() {
var Model = Backbone.Model.extend({
initialize: function(attrs, options) {
this.model_parameter = options.model_parameter;
}
});
var col = new (Backbone.Collection.extend({ model: Model }))();
col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
equal(col.length, 2);
col.each(function(model) {
equal(model.model_parameter, 'model parameter');
});
});
test("trigger custom events on models", 1, function() {
var fired = null;
a.on("custom", function() { fired = true; });
a.trigger("custom");
equal(fired, true);
});
test("add does not alter arguments", 2, function(){
var attrs = {};
var models = [attrs];
new Backbone.Collection().add(models);
equal(models.length, 1);
ok(attrs === models[0]);
});
test("#714: access `model.collection` in a brand new model.", 2, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
var Model = Backbone.Model.extend({
set: function(attrs) {
equal(attrs.prop, 'value');
equal(this.collection, collection);
return this;
}
});
collection.model = Model;
collection.create({prop: 'value'});
});
test("#574, remove its own reference to the .models array.", 2, function() {
var col = new Backbone.Collection([
{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
]);
equal(col.length, 6);
col.remove(col.models);
equal(col.length, 0);
});
test("#861, adding models to a collection which do not pass validation, with validate:true", function() {
var Model = Backbone.Model.extend({
validate: function(attrs) {
if (attrs.id == 3) return "id can't be 3";
}
});
var Collection = Backbone.Collection.extend({
model: Model
});
var collection = new Collection;
collection.on("error", function() { ok(true); });
collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
});
test("Invalid models are discarded with validate:true.", 5, function() {
var collection = new Backbone.Collection;
collection.on('test', function() { ok(true); });
collection.model = Backbone.Model.extend({
validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
});
var model = new collection.model({id: 1, valid: true});
collection.add([model, {id: 2}], {validate:true});
model.trigger('test');
ok(collection.get(model.cid));
ok(collection.get(1));
ok(!collection.get(2));
equal(collection.length, 1);
});
test("multiple copies of the same model", 3, function() {
var col = new Backbone.Collection();
var model = new Backbone.Model();
col.add([model, model]);
equal(col.length, 1);
col.add([{id: 1}, {id: 1}]);
equal(col.length, 2);
equal(col.last().id, 1);
});
test("#964 - collection.get return inconsistent", 2, function() {
var c = new Backbone.Collection();
ok(c.get(null) === undefined);
ok(c.get() === undefined);
});
test("#1112 - passing options.model sets collection.model", 2, function() {
var Model = Backbone.Model.extend({});
var c = new Backbone.Collection([{id: 1}], {model: Model});
ok(c.model === Model);
ok(c.at(0) instanceof Model);
});
test("null and undefined are invalid ids.", 2, function() {
var model = new Backbone.Model({id: 1});
var collection = new Backbone.Collection([model]);
model.set({id: null});
ok(!collection.get('null'));
model.set({id: 1});
model.set({id: undefined});
ok(!collection.get('undefined'));
});
test("falsy comparator", 4, function(){
var Col = Backbone.Collection.extend({
comparator: function(model){ return model.id; }
});
var col = new Col();
var colFalse = new Col(null, {comparator: false});
var colNull = new Col(null, {comparator: null});
var colUndefined = new Col(null, {comparator: undefined});
ok(col.comparator);
ok(!colFalse.comparator);
ok(!colNull.comparator);
ok(colUndefined.comparator);
});
test("#1355 - `options` is passed to success callbacks", 2, function(){
var m = new Backbone.Model({x:1});
var col = new Backbone.Collection();
var opts = {
success: function(collection, resp, options){
ok(options);
}
};
col.sync = m.sync = function( method, collection, options ){
options.success(collection, [], options);
};
col.fetch(opts);
col.create(m, opts);
});
test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
var collection = new Backbone.Collection;
collection.url = '/test';
Backbone.ajax = function(settings){ settings.success(); };
collection.on('request', function(obj, xhr, options) {
ok(obj === collection, "collection has correct 'request' event after fetching");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection, "collection has correct 'sync' event after fetching");
});
collection.fetch();
collection.off();
collection.on('request', function(obj, xhr, options) {
ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
});
collection.on('sync', function(obj, response, options) {
ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
});
collection.create({id: 1});
collection.off();
});
test("#1447 - create with wait adds model.", 1, function() {
var collection = new Backbone.Collection;
var model = new Backbone.Model;
model.sync = function(method, model, options){ options.success(); };
collection.on('add', function(){ ok(true); });
collection.create(model, {wait: true});
});
test("#1448 - add sorts collection after merge.", 1, function() {
var collection = new Backbone.Collection([
{id: 1, x: 1},
{id: 2, x: 2}
]);
collection.comparator = function(model){ return model.get('x'); };
collection.add({id: 1, x: 3}, {merge: true});
deepEqual(collection.pluck('id'), [2, 1]);
});
test("#1655 - groupBy can be used with a string argument.", 3, function() {
var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
var grouped = collection.groupBy('x');
strictEqual(_.keys(grouped).length, 2);
strictEqual(grouped[1][0].get('x'), 1);
strictEqual(grouped[2][0].get('x'), 2);
});
test("#1655 - sortBy can be used with a string argument.", 1, function() {
var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
var values = _.map(collection.sortBy('x'), function(model) {
return model.get('x');
});
deepEqual(values, [1, 2, 3]);
});
test("#1604 - Removal during iteration.", 0, function() {
var collection = new Backbone.Collection([{}, {}]);
collection.on('add', function() {
collection.at(0).destroy();
});
collection.add({}, {at: 0});
});
test("#1638 - `sort` during `add` triggers correctly.", function() {
var collection = new Backbone.Collection;
collection.comparator = function(model) { return model.get('x'); };
var added = [];
collection.on('add', function(model) {
model.set({x: 3});
collection.sort();
added.push(model.id);
});
collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
deepEqual(added, [1, 2]);
});
test("fetch parses models by default", 1, function() {
var model = {};
var Collection = Backbone.Collection.extend({
url: 'test',
model: Backbone.Model.extend({
parse: function(resp) {
strictEqual(resp, model);
}
})
});
new Collection().fetch();
this.ajaxSettings.success([model]);
});
test("`sort` shouldn't always fire on `add`", 1, function() {
var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
comparator: 'id'
});
c.sort = function(){ ok(true); };
c.add([]);
c.add({id: 1});
c.add([{id: 2}, {id: 3}]);
c.add({id: 4});
});
test("#1407 parse option on constructor parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("#1407 parse option on reset parses collection and models", 2, function() {
var model = {
namespace : [{id: 1}, {id:2}]
};
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({
parse: function(model) {
model.name = 'test';
return model;
}
}),
parse: function(model) {
return model.namespace;
}
});
var c = new Collection();
c.reset(model, {parse:true});
equal(c.length, 2);
equal(c.at(0).get('name'), 'test');
});
test("Reset includes previous models in triggered event.", 1, function() {
var model = new Backbone.Model();
var collection = new Backbone.Collection([model])
.on('reset', function(collection, options) {
deepEqual(options.previousModels, [model]);
});
collection.reset([]);
});
test("set", function() {
var m1 = new Backbone.Model();
var m2 = new Backbone.Model({id: 2});
var m3 = new Backbone.Model();
var c = new Backbone.Collection([m1, m2]);
// Test add/change/remove events
c.on('add', function(model) {
strictEqual(model, m3);
});
c.on('change', function(model) {
strictEqual(model, m2);
});
c.on('remove', function(model) {
strictEqual(model, m1);
});
// remove: false doesn't remove any models
c.set([], {remove: false});
strictEqual(c.length, 2);
// add: false doesn't add any models
c.set([m1, m2, m3], {add: false});
strictEqual(c.length, 2);
// merge: false doesn't change any models
c.set([m1, {id: 2, a: 1}], {merge: false});
strictEqual(m2.get('a'), void 0);
// add: false, remove: false only merges existing models
c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 0);
// default options add/remove/merge as appropriate
c.set([{id: 2, a: 1}, m3]);
strictEqual(c.length, 2);
strictEqual(m2.get('a'), 1);
// Test removing models not passing an argument
c.off('remove').on('remove', function(model) {
ok(model === m2 || model === m3);
});
c.set([]);
strictEqual(c.length, 0);
});
test("set with only cids", 3, function() {
var m1 = new Backbone.Model;
var m2 = new Backbone.Model;
var c = new Backbone.Collection;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set with only idAttribute", 3, function() {
var m1 = { _id: 1 };
var m2 = { _id: 2 };
var col = Backbone.Collection.extend({
model: Backbone.Model.extend({
idAttribute: '_id'
})
});
var c = new col;
c.set([m1, m2]);
equal(c.length, 2);
c.set([m1]);
equal(c.length, 1);
c.set([m1, m1, m1, m2, m2], {remove: false});
equal(c.length, 2);
});
test("set + merge with default values defined", function() {
var Model = Backbone.Model.extend({
defaults: {
key: 'value'
}
});
var m = new Model({id: 1});
var col = new Backbone.Collection([m], {model: Model});
equal(col.first().get('key'), 'value');
col.set({id: 1, key: 'other'});
equal(col.first().get('key'), 'other');
col.set({id: 1, other: 'value'});
equal(col.first().get('key'), 'other');
equal(col.length, 1);
});
test('merge without mutation', function () {
var Model = Backbone.Model.extend({
initialize: function (attrs, options) {
if (attrs.child) {
this.set('child', new Model(attrs.child, options), options);
}
}
});
var Collection = Backbone.Collection.extend({model: Model});
var data = [{id: 1, child: {id: 2}}];
var collection = new Collection(data);
equal(collection.first().id, 1);
collection.set(data);
equal(collection.first().id, 1);
collection.set([{id: 2, child: {id: 2}}].concat(data));
deepEqual(collection.pluck('id'), [2, 1]);
});
test("`set` and model level `parse`", function() {
var Model = Backbone.Model.extend({
parse: function (res) { return res.model; }
});
var Collection = Backbone.Collection.extend({
model: Model,
parse: function (res) { return res.models; }
});
var model = new Model({id: 1});
var collection = new Collection(model);
collection.set({models: [
{model: {id: 1}},
{model: {id: 2}}
]}, {parse: true});
equal(collection.first(), model);
});
test("`set` data is only parsed once", function() {
var collection = new Backbone.Collection();
collection.model = Backbone.Model.extend({
parse: function (data) {
equal(data.parsed, void 0);
data.parsed = true;
return data;
}
});
collection.set({}, {parse: true});
});
test('`set` matches input order in the absence of a comparator', function () {
var one = new Backbone.Model({id: 1});
var two = new Backbone.Model({id: 2});
var three = new Backbone.Model({id: 3});
var collection = new Backbone.Collection([one, two, three]);
collection.set([{id: 3}, {id: 2}, {id: 1}]);
deepEqual(collection.models, [three, two, one]);
collection.set([{id: 1}, {id: 2}]);
deepEqual(collection.models, [one, two]);
collection.set([two, three, one]);
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}], {remove: false});
deepEqual(collection.models, [two, three, one]);
collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
deepEqual(collection.models, [one, two, three]);
collection.set([three, two, one, {id: 4}], {add: false});
deepEqual(collection.models, [one, two, three]);
});
test("#1894 - Push should not trigger a sort", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() {
ok(false);
}
});
new Collection().push({id: 1});
});
test("`set` with non-normal id", function() {
var Collection = Backbone.Collection.extend({
model: Backbone.Model.extend({idAttribute: '_id'})
});
var collection = new Collection({_id: 1});
collection.set([{_id: 1, a: 1}], {add: false});
equal(collection.first().get('a'), 1);
});
test("#1894 - `sort` can optionally be turned off", 0, function() {
var Collection = Backbone.Collection.extend({
comparator: 'id',
sort: function() { ok(true); }
});
new Collection().add({id: 1}, {sort: false});
});
test("#1915 - `parse` data in the right order in `set`", function() {
var collection = new (Backbone.Collection.extend({
parse: function (data) {
strictEqual(data.status, 'ok');
return data.data;
}
}));
var res = {status: 'ok', data:[{id: 1}]};
collection.set(res, {parse: true});
});
asyncTest("#1939 - `parse` is passed `options`", 1, function () {
var collection = new (Backbone.Collection.extend({
url: '/',
parse: function (data, options) {
strictEqual(options.xhr.someHeader, 'headerValue');
return data;
}
}));
var ajax = Backbone.ajax;
Backbone.ajax = function (params) {
_.defer(params.success);
return {someHeader: 'headerValue'};
};
collection.fetch({
success: function () { start(); }
});
Backbone.ajax = ajax;
});
test("`add` only `sort`s when necessary", 2, function () {
var collection = new (Backbone.Collection.extend({
comparator: 'a'
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("`add` only `sort`s when necessary with comparator function", 3, function () {
var collection = new (Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
}
}))([{id: 1}, {id: 2}, {id: 3}]);
collection.on('sort', function () { ok(true); });
collection.add({id: 4}); // do sort, new model
collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
collection.add(collection.models); // don't sort, nothing new
collection.add(collection.models, {merge: true}); // don't sort
});
test("Attach options to collection.", 2, function() {
var model = new Backbone.Model;
var comparator = function(){};
var collection = new Backbone.Collection([], {
model: model,
comparator: comparator
});
ok(collection.model === model);
ok(collection.comparator === comparator);
});
test("`add` overrides `set` flags", function () {
var collection = new Backbone.Collection();
collection.once('add', function (model, collection, options) {
collection.add({id: 2}, options);
});
collection.set({id: 1});
equal(collection.length, 2);
});
test("#2606 - Collection#create, success arguments", 1, function() {
var collection = new Backbone.Collection;
collection.url = 'test';
collection.create({}, {
success: function(model, resp, options) {
strictEqual(resp, 'response');
}
});
this.ajaxSettings.success('response');
});
});
| mit |
tomasy23/evertonkrosnodart | tools/editor/plugins/control_editor_plugin.cpp | 22889 | /*************************************************************************/
/* control_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/*************************************************************************/
#if 0
#include "control_editor_plugin.h"
#include "print_string.h"
#include "editor_node.h"
#include "os/keyboard.h"
#include "scene/main/viewport.h"
void ControlEditor::_add_control(Control *p_control,const EditInfo& p_info) {
if (controls.has(p_control))
return;
controls.insert(p_control,p_info);
p_control->call_deferred("connect","visibility_changed",this,"_visibility_changed",varray(p_control->get_instance_ID()));
}
void ControlEditor::_remove_control(Control *p_control) {
p_control->call_deferred("disconnect","visibility_changed",this,"_visibility_changed");
controls.erase(p_control);
}
void ControlEditor::_clear_controls(){
while(controls.size())
_remove_control(controls.front()->key());
}
void ControlEditor::_visibility_changed(ObjectID p_control) {
Object *c = ObjectDB::get_instance(p_control);
if (!c)
return;
Control *ct = c->cast_to<Control>();
if (!ct)
return;
_remove_control(ct);
}
void ControlEditor::_node_removed(Node *p_node) {
Control *control = (Control*)p_node; //not a good cast, but safe
if (controls.has(control))
_remove_control(control);
if (current_window==p_node) {
_clear_controls();
}
update();
}
// slow as hell
Control* ControlEditor::_select_control_at_pos(const Point2& p_pos,Node* p_node) {
for (int i=p_node->get_child_count()-1;i>=0;i--) {
Control *r=_select_control_at_pos(p_pos,p_node->get_child(i));
if (r)
return r;
}
Control *c=p_node->cast_to<Control>();
if (c) {
Rect2 rect = c->get_window_rect();
if (c->get_window()==current_window) {
rect.pos=transform.xform(rect.pos).floor();
}
if (rect.has_point(p_pos))
return c;
}
return NULL;
}
void ControlEditor::_key_move(const Vector2& p_dir, bool p_snap) {
if (drag!=DRAG_NONE)
return;
Vector2 motion=p_dir;
if (p_snap)
motion*=snap_val->get_text().to_double();
undo_redo->create_action("Edit Control");
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
undo_redo->add_do_method(control,"set_pos",control->get_pos()+motion);
undo_redo->add_undo_method(control,"set_pos",control->get_pos());
}
undo_redo->commit_action();
}
void ControlEditor::_input_event(InputEvent p_event) {
if (p_event.type==InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &b=p_event.mouse_button;
if (b.button_index==BUTTON_RIGHT) {
if (controls.size() && drag!=DRAG_NONE) {
//cancel drag
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
control->set_pos(E->get().drag_pos);
control->set_size(E->get().drag_size);
}
} else if (b.pressed) {
popup->set_pos(Point2(b.x,b.y));
popup->popup();
}
return;
}
//if (!controls.size())
// return;
if (b.button_index!=BUTTON_LEFT)
return;
if (!b.pressed) {
if (drag!=DRAG_NONE) {
if (undo_redo) {
undo_redo->create_action("Edit Control");
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
undo_redo->add_do_method(control,"set_pos",control->get_pos());
undo_redo->add_do_method(control,"set_size",control->get_size());
undo_redo->add_undo_method(control,"set_pos",E->get().drag_pos);
undo_redo->add_undo_method(control,"set_size",E->get().drag_size);
}
undo_redo->commit_action();
}
drag=DRAG_NONE;
}
return;
}
if (controls.size()==1) {
//try single control edit
Control *control = controls.front()->key();
ERR_FAIL_COND(!current_window);
Rect2 rect=control->get_window_rect();
Point2 ofs=Point2();//get_global_pos();
Rect2 draw_rect=Rect2(rect.pos-ofs,rect.size);
Point2 click=Point2(b.x,b.y);
click = transform.affine_inverse().xform(click);
Size2 handle_size=Size2(handle_len,handle_len);
drag = DRAG_NONE;
if (Rect2(draw_rect.pos-handle_size,handle_size).has_point(click))
drag=DRAG_TOP_LEFT;
else if (Rect2(draw_rect.pos+draw_rect.size,handle_size).has_point(click))
drag=DRAG_BOTTOM_RIGHT;
else if(Rect2(draw_rect.pos+Point2(draw_rect.size.width,-handle_size.y),handle_size).has_point(click))
drag=DRAG_TOP_RIGHT;
else if (Rect2(draw_rect.pos+Point2(-handle_size.x,draw_rect.size.height),handle_size).has_point(click))
drag=DRAG_BOTTOM_LEFT;
else if (Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),-handle_size.height),handle_size).has_point(click))
drag=DRAG_TOP;
else if( Rect2(draw_rect.pos+Point2(-handle_size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size).has_point(click))
drag=DRAG_LEFT;
else if ( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),draw_rect.size.height),handle_size).has_point(click))
drag=DRAG_BOTTOM;
else if( Rect2(draw_rect.pos+Point2(draw_rect.size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size).has_point(click))
drag=DRAG_RIGHT;
if (drag!=DRAG_NONE) {
drag_from=click;
controls[control].drag_pos=control->get_pos();
controls[control].drag_size=control->get_size();
controls[control].drag_limit=drag_from+controls[control].drag_size-control->get_minimum_size();
return;
}
}
//multi control edit
Point2 click=Point2(b.x,b.y);
Node* scene = get_scene()->get_root_node()->cast_to<EditorNode>()->get_edited_scene();
if (!scene)
return;
/*
if (current_window) {
//no window.... ?
click-=current_window->get_scroll();
}*/
Control *c=_select_control_at_pos(click, scene);
Node* n = c;
while ((n && n != scene && n->get_owner() != scene) || (n && !n->is_type("Control"))) {
n = n->get_parent();
};
c = n->cast_to<Control>();
if (b.mod.control) { //additive selection
if (!c)
return; //nothing to add
if (current_window && controls.size() && c->get_window()!=current_window)
return; //cant multiple select from multiple windows
if (!controls.size())
current_window=c->get_window();
if (controls.has(c)) {
//already in here, erase it
_remove_control(c);
update();
return;
}
//check parents!
Control *parent = c->get_parent()->cast_to<Control>();
while(parent) {
if (controls.has(parent))
return; //a parent is already selected, so this is pointless
parent=parent->get_parent()->cast_to<Control>();
}
//check childrens of everything!
List<Control*> to_erase;
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
parent = E->key()->get_parent()->cast_to<Control>();
while(parent) {
if (parent==c) {
to_erase.push_back(E->key());
break;
}
parent=parent->get_parent()->cast_to<Control>();
}
}
while(to_erase.size()) {
_remove_control(to_erase.front()->get());
to_erase.pop_front();
}
_add_control(c,EditInfo());
update();
} else {
//regular selection
if (!c) {
_clear_controls();
update();
return;
}
if (!controls.has(c)) {
_clear_controls();
current_window=c->get_window();
_add_control(c,EditInfo());
//reselect
if (get_scene()->is_editor_hint()) {
get_scene()->get_root_node()->call("edit_node",c);
}
}
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
EditInfo &ei=E->get();
Control *control=E->key();
ei.drag_pos=control->get_pos();
ei.drag_size=control->get_size();
ei.drag_limit=drag_from+ei.drag_size-control->get_minimum_size();
}
drag=DRAG_ALL;
drag_from=click;
update();
}
}
if (p_event.type==InputEvent::MOUSE_MOTION) {
const InputEventMouseMotion &m=p_event.mouse_motion;
if (drag==DRAG_NONE || !current_window)
return;
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
Point2 control_drag_pos=E->get().drag_pos;
Point2 control_drag_size=E->get().drag_size;
Point2 control_drag_limit=E->get().drag_limit;
Point2 pos=Point2(m.x,m.y);
pos = transform.affine_inverse().xform(pos);
switch(drag) {
case DRAG_ALL: {
control->set_pos( snapify(control_drag_pos+(pos-drag_from)) );
} break;
case DRAG_RIGHT: {
control->set_size( snapify(Size2(control_drag_size.width+(pos-drag_from).x,control_drag_size.height)) );
} break;
case DRAG_BOTTOM: {
control->set_size( snapify(Size2(control_drag_size.width,control_drag_size.height+(pos-drag_from).y)) );
} break;
case DRAG_BOTTOM_RIGHT: {
control->set_size( snapify(control_drag_size+(pos-drag_from)) );
} break;
case DRAG_TOP_LEFT: {
if(pos.x>control_drag_limit.x)
pos.x=control_drag_limit.x;
if(pos.y>control_drag_limit.y)
pos.y=control_drag_limit.y;
Point2 old_size = control->get_size();
Point2 new_pos = snapify(control_drag_pos+(pos-drag_from));
Point2 new_size = old_size + (control->get_pos() - new_pos);
control->set_pos( new_pos );
control->set_size( new_size );
} break;
case DRAG_TOP: {
if(pos.y>control_drag_limit.y)
pos.y=control_drag_limit.y;
Point2 old_size = control->get_size();
Point2 new_pos = snapify(control_drag_pos+Point2(0,pos.y-drag_from.y));
Point2 new_size = old_size + (control->get_pos() - new_pos);
control->set_pos( new_pos );
control->set_size( new_size );
} break;
case DRAG_LEFT: {
if(pos.x>control_drag_limit.x)
pos.x=control_drag_limit.x;
Point2 old_size = control->get_size();
Point2 new_pos = snapify(control_drag_pos+Point2(pos.x-drag_from.x,0));
Point2 new_size = old_size + (control->get_pos() - new_pos);
control->set_pos( new_pos );
control->set_size( new_size );
} break;
case DRAG_TOP_RIGHT: {
if(pos.y>control_drag_limit.y)
pos.y=control_drag_limit.y;
Point2 old_size = control->get_size();
Point2 new_pos = snapify(control_drag_pos+Point2(0,pos.y-drag_from.y));
float new_size_y = Point2( old_size + (control->get_pos() - new_pos)).y;
float new_size_x = snapify(control_drag_size+Point2(pos.x-drag_from.x,0)).x;
control->set_pos( new_pos );
control->set_size( Point2(new_size_x, new_size_y) );
} break;
case DRAG_BOTTOM_LEFT: {
if(pos.x>control_drag_limit.x)
pos.x=control_drag_limit.x;
Point2 old_size = control->get_size();
Point2 new_pos = snapify(control_drag_pos+Point2(pos.x-drag_from.x,0));
float new_size_y = snapify(control_drag_size+Point2(0,pos.y-drag_from.y)).y;
float new_size_x = Point2( old_size + (control->get_pos() - new_pos)).x;
control->set_pos( new_pos );
control->set_size( Point2(new_size_x, new_size_y) );
} break;
default:{}
}
}
}
if (p_event.type==InputEvent::KEY) {
const InputEventKey &k=p_event.key;
if (k.pressed) {
if (k.scancode==KEY_UP)
_key_move(Vector2(0,-1),k.mod.shift);
else if (k.scancode==KEY_DOWN)
_key_move(Vector2(0,1),k.mod.shift);
else if (k.scancode==KEY_LEFT)
_key_move(Vector2(-1,0),k.mod.shift);
else if (k.scancode==KEY_RIGHT)
_key_move(Vector2(1,0),k.mod.shift);
}
}
}
bool ControlEditor::get_remove_list(List<Node*> *p_list) {
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
p_list->push_back(E->key());
}
return !p_list->empty();
}
void ControlEditor::_update_scroll(float) {
if (updating_scroll)
return;
if (!current_window)
return;
Point2 ofs;
ofs.x=h_scroll->get_val();
ofs.y=v_scroll->get_val();
// current_window->set_scroll(-ofs);
transform=Matrix32();
transform.scale_basis(Size2(zoom,zoom));
transform.elements[2]=-ofs*zoom;
RID viewport = editor->get_scene_root()->get_viewport();
VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport,transform);
update();
}
void ControlEditor::_notification(int p_what) {
if (p_what==NOTIFICATION_PROCESS) {
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
Rect2 r=control->get_window_rect();
if (r != E->get().last_rect ) {
update();
E->get().last_rect=r;
}
}
}
if (p_what==NOTIFICATION_CHILDREN_CONFIGURED) {
get_scene()->connect("node_removed",this,"_node_removed");
}
if (p_what==NOTIFICATION_DRAW) {
// TODO fetch the viewport?
/*
if (!control) {
h_scroll->hide();
v_scroll->hide();
return;
}
*/
_update_scrollbars();
if (!current_window)
return;
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
Rect2 rect=control->get_window_rect();
RID ci=get_canvas_item();
VisualServer::get_singleton()->canvas_item_set_clip(ci,true);
Point2 ofs=Point2();//get_global_pos();
Rect2 draw_rect=Rect2(rect.pos-ofs,rect.size);
draw_rect.pos = transform.xform(draw_rect.pos);
Color light_edit_color=Color(1.0,0.8,0.8);
Color dark_edit_color=Color(0.4,0.1,0.1);
Size2 handle_size=Size2(handle_len,handle_len);
#define DRAW_RECT( m_rect, m_color )\
VisualServer::get_singleton()->canvas_item_add_rect(ci,m_rect,m_color);
#define DRAW_EMPTY_RECT( m_rect, m_color )\
DRAW_RECT( Rect2(m_rect.pos,Size2(m_rect.size.width,1)), m_color );\
DRAW_RECT(Rect2(Point2(m_rect.pos.x,m_rect.pos.y+m_rect.size.height-1),Size2(m_rect.size.width,1)), m_color);\
DRAW_RECT(Rect2(m_rect.pos,Size2(1,m_rect.size.height)), m_color);\
DRAW_RECT(Rect2(Point2(m_rect.pos.x+m_rect.size.width-1,m_rect.pos.y),Size2(1,m_rect.size.height)), m_color);
#define DRAW_BORDER_RECT( m_rect, m_border_color,m_color )\
DRAW_RECT( m_rect, m_color );\
DRAW_EMPTY_RECT( m_rect, m_border_color );
DRAW_EMPTY_RECT( draw_rect.grow(2), light_edit_color );
DRAW_EMPTY_RECT( draw_rect.grow(1), dark_edit_color );
if (controls.size()==1) {
DRAW_BORDER_RECT( Rect2(draw_rect.pos-handle_size,handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+draw_rect.size,handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(draw_rect.size.width,-handle_size.y),handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(-handle_size.x,draw_rect.size.height),handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),-handle_size.height),handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(-handle_size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),draw_rect.size.height),handle_size), light_edit_color,dark_edit_color );
DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(draw_rect.size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size), light_edit_color,dark_edit_color );
}
//DRAW_EMPTY_RECT( Rect2( current_window->get_scroll()-Point2(1,1), get_size()+Size2(2,2)), Color(0.8,0.8,1.0,0.8) );
E->get().last_rect = rect;
}
}
}
void ControlEditor::edit(Control *p_control) {
drag=DRAG_NONE;
_clear_controls();
_add_control(p_control,EditInfo());
current_window=p_control->get_window();
update();
}
void ControlEditor::_find_controls_span(Node *p_node, Rect2& r_rect) {
if (!editor->get_scene())
return;
if (p_node!=editor->get_edited_scene() && p_node->get_owner()!=editor->get_edited_scene())
return;
if (p_node->cast_to<Control>()) {
Control *c = p_node->cast_to<Control>();
if (c->get_viewport() != editor->get_viewport()->get_viewport())
return; //bye, it's in another viewport
if (!c->get_parent_control()) {
Rect2 span = c->get_subtree_span_rect();
r_rect.merge(span);
}
}
for(int i=0;i<p_node->get_child_count();i++) {
_find_controls_span(p_node->get_child(i),r_rect);
}
}
void ControlEditor::_update_scrollbars() {
if (!editor->get_scene()) {
h_scroll->hide();
v_scroll->hide();
return;
}
updating_scroll=true;
Size2 size = get_size();
Size2 hmin = h_scroll->get_minimum_size();
Size2 vmin = v_scroll->get_minimum_size();
v_scroll->set_begin( Point2(size.width - vmin.width, 0) );
v_scroll->set_end( Point2(size.width, size.height) );
h_scroll->set_begin( Point2( 0, size.height - hmin.height) );
h_scroll->set_end( Point2(size.width-vmin.width, size.height) );
Rect2 local_rect = Rect2(Point2(),get_size()-Size2(vmin.width,hmin.height));
Rect2 control_rect=local_rect;
if (editor->get_edited_scene())
_find_controls_span(editor->get_edited_scene(),control_rect);
control_rect.pos*=zoom;
control_rect.size*=zoom;
/*
for(ControlMap::Element *E=controls.front();E;E=E->next()) {
Control *control = E->key();
Rect2 r = control->get_window()->get_subtree_span_rect();
if (E==controls.front()) {
control_rect = r.merge(local_rect);
} else {
control_rect = control_rect.merge(r);
}
}
*/
Point2 ofs;
if (control_rect.size.height <= local_rect.size.height) {
v_scroll->hide();
ofs.y=0;
} else {
v_scroll->show();
v_scroll->set_min(control_rect.pos.y);
v_scroll->set_max(control_rect.pos.y+control_rect.size.y);
v_scroll->set_page(local_rect.size.y);
ofs.y=-v_scroll->get_val();
}
if (control_rect.size.width <= local_rect.size.width) {
h_scroll->hide();
ofs.x=0;
} else {
h_scroll->show();
h_scroll->set_min(control_rect.pos.x);
h_scroll->set_max(control_rect.pos.x+control_rect.size.x);
h_scroll->set_page(local_rect.size.x);
ofs.x=-h_scroll->get_val();
}
// transform=Matrix32();
transform.elements[2]=ofs*zoom;
RID viewport = editor->get_scene_root()->get_viewport();
VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport,transform);
// transform.scale_basis(Vector2(zoom,zoom));
updating_scroll=false;
}
Point2i ControlEditor::snapify(const Point2i& p_pos) const {
bool active=popup->is_item_checked(0);
int snap = snap_val->get_text().to_int();
if (!active || snap<1)
return p_pos;
Point2i pos=p_pos;
pos.x-=pos.x%snap;
pos.y-=pos.y%snap;
return pos;
}
void ControlEditor::_popup_callback(int p_op) {
switch(p_op) {
case SNAP_USE: {
popup->set_item_checked(0,!popup->is_item_checked(0));
} break;
case SNAP_CONFIGURE: {
snap_dialog->popup_centered(Size2(200,85));
} break;
}
}
void ControlEditor::_bind_methods() {
ObjectTypeDB::bind_method("_input_event",&ControlEditor::_input_event);
ObjectTypeDB::bind_method("_node_removed",&ControlEditor::_node_removed);
ObjectTypeDB::bind_method("_update_scroll",&ControlEditor::_update_scroll);
ObjectTypeDB::bind_method("_popup_callback",&ControlEditor::_popup_callback);
ObjectTypeDB::bind_method("_visibility_changed",&ControlEditor::_visibility_changed);
}
ControlEditor::ControlEditor(EditorNode *p_editor) {
editor=p_editor;
h_scroll = memnew( HScrollBar );
v_scroll = memnew( VScrollBar );
add_child(h_scroll);
add_child(v_scroll);
h_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),true);
v_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),true);
updating_scroll=false;
set_focus_mode(FOCUS_ALL);
handle_len=10;
popup=memnew( PopupMenu );
popup->add_check_item("Use Snap");
popup->add_item("Configure Snap..");
add_child(popup);
snap_dialog = memnew( ConfirmationDialog );
snap_dialog->get_ok()->hide();
snap_dialog->get_cancel()->set_text("Close");
add_child(snap_dialog);
Label *l = memnew(Label);
l->set_text("Snap:");
l->set_pos(Point2(5,5));
snap_dialog->add_child(l);
snap_val=memnew(LineEdit);
snap_val->set_text("5");
snap_val->set_anchor(MARGIN_RIGHT,ANCHOR_END);
snap_val->set_begin(Point2(15,25));
snap_val->set_end(Point2(10,25));
snap_dialog->add_child(snap_val);
popup->connect("item_pressed", this,"_popup_callback");
current_window=NULL;
zoom=0.5;
}
void ControlEditorPlugin::edit(Object *p_object) {
control_editor->set_undo_redo(&get_undo_redo());
control_editor->edit(p_object->cast_to<Control>());
}
bool ControlEditorPlugin::handles(Object *p_object) const {
return p_object->is_type("Control");
}
void ControlEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
control_editor->show();
control_editor->set_process(true);
} else {
control_editor->hide();
control_editor->set_process(false);
}
}
ControlEditorPlugin::ControlEditorPlugin(EditorNode *p_node) {
editor=p_node;
control_editor = memnew( ControlEditor(editor) );
editor->get_viewport()->add_child(control_editor);
control_editor->set_area_as_parent_rect();
control_editor->hide();
}
ControlEditorPlugin::~ControlEditorPlugin()
{
}
#endif
| mit |
praeclarum/Netjs | Netjs/Dependencies/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertLambdaBodyExpressionToStatementAction.cs | 2431 | //
// ConvertLambdaBodyExpressionToStatementAction.cs
//
// Author:
// Mansheng Yang <[email protected]>
//
// Copyright (c) 2012 Mansheng Yang <[email protected]>
//
// 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.
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[ContextAction ("Converts expression of lambda body to statement",
Description = "Converts expression of lambda body to statement")]
public class ConvertLambdaBodyExpressionToStatementAction : SpecializedCodeAction<LambdaExpression>
{
protected override CodeAction GetAction (RefactoringContext context, LambdaExpression node)
{
if (!node.ArrowToken.Contains (context.Location))
return null;
var bodyExpr = node.Body as Expression;
if (bodyExpr == null)
return null;
return new CodeAction (context.TranslateString ("Convert to lambda statement"),
script =>
{
var body = new BlockStatement ();
if (RequireReturnStatement (context, node)) {
body.Add (new ReturnStatement (bodyExpr.Clone ()));
} else {
body.Add (new ExpressionStatement (bodyExpr.Clone ()));
}
script.Replace (bodyExpr, body);
});
}
static bool RequireReturnStatement (RefactoringContext context, LambdaExpression lambda)
{
var type = LambdaHelper.GetLambdaReturnType (context, lambda);
return type != null && type.ReflectionName != "System.Void";
}
}
}
| mit |
louisgv/eat | www/lib/angular-tooltips/index.html | 14939 | <!doctype html>
<html ng-app="720kb">
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="dist/angular-tooltips.css">
<style media="screen">
body {
margin: 100px;
}
.scroll-area {
max-height: 90px;
overflow: hidden;
overflow-y: scroll;
background: grey;
}
.scroll-area-horizontal {
padding: 10px;
max-width: 90px;
overflow: hidden;
overflow-x: scroll;
background: grey;
display: flex;
}
#demo-container > div {
margin: 10% 0;
}
.a-class {
font-size: 2em;
}
.another-class {
color: violet;
}
</style>
<title>Angularjs Tooltips</title>
</head>
<body id="demo-container" ng-controller="DemoCtrl as demoCtrl">
<div>
<i class="fa fa-bolt"
tooltips
tooltip-append-to-body="true"
tooltip-template="I'm a tooltip that is bounded on body!"></i>
</div>
<div>
<i class="fa fa-code"
tooltips
tooltip-hidden="{{ demoCtrl.isHidden }}"
tooltip-template="I'm a tooltip that was hidden!"></i>
</div>
<div>
<i class="fa fa-recycle"
tooltips
tooltip-template="<h3>Stuff</h3> me <br> me <br>"></i>
</div>
<div>
<i class="fa fa-file"
tooltips
tooltip-template="I'm a tooltip!"></i>
</div>
<div>
<i class="fa fa-list"
tooltips
tooltip-side="left"
tooltip-template="I'm another tooltip!"></i>
</div>
<div>
<i class="fa fa-hourglass-end"
tooltips
tooltip-side="bottom"
tooltip-template="I'm another tooltip!"></i>
</div>
<div>
<i class="fa fa-map"
tooltips
tooltip-side="right"
tooltip-template="I'm another tooltip!"></i>
</div>
<div>
<span tooltips
tooltip-template="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.">
I'm a tooltip content.
</span>
</div>
<div>
<span tooltips
tooltip-side="left"
tooltip-template="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.">
I'm a tooltip content.
</span>
</div>
<div>
<span tooltips
tooltip-side="bottom"
tooltip-template="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.">
I'm a tooltip content.
</span>
</div>
<div>
<span tooltips
tooltip-side="right"
tooltip-template="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.">
I'm a tooltip content.
</span>
</div>
<div>
<span tooltips
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="left"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="bottom"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="right"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-smart="true"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="left"
tooltip-smart="true"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="bottom"
tooltip-smart="true"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-side="right"
tooltip-smart="true"
tooltip-template="I'm a tooltip!">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tincidunt dolor eu nunc interdum vulputate. Integer non lorem nec libero consequat faucibus eu vitae sem. Etiam sit amet nulla aliquam erat pellentesque dictum non quis dui. Phasellus in lorem sed magna condimentum accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec rutrum tristique scelerisque. Nam lorem neque, feugiat quis odio sed, dignissim commodo massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse sapien sem, lobortis non erat eu, convallis finibus ante.
</span>
</div>
<div>
<span tooltips
tooltip-template="{{ demoCtrl.tooltipText }}">
I'm a tooltip content.
</span>
</div>
<div>
<span tooltips
tooltip-template="{{ demoCtrl.tooltipText }}">
{{ demoCtrl.tooltipContentText }}
</span>
</div>
<div>
<span tooltips
tooltip-class="a-class"
tooltip-template="{{ demoCtrl.tooltipText }}">
{{ demoCtrl.tooltipContentText }}
</span>
</div>
<div>
<span tooltips
tooltip-class="{{ demoCtrl.class }}"
tooltip-template="{{ demoCtrl.tooltipText }}">
{{ demoCtrl.tooltipContentText }}
</span>
</div>
<div>
<span tooltips
tooltip-template-url="demo/views/index-with-embedded-controller.html">
{{ demoCtrl.tooltipContentText }}
</span>
</div>
<div>
<span tooltips
tooltip-template-url="demo/views/index-without-embedded-controller.html"
tooltip-controller="Ctrl as ctrl">
{{ demoCtrl.tooltipContentText }}
</span>
</div>
<div>
<span tooltips
tooltip-close-button="true"
tooltip-template="a tooltip text"
tooltip-hide-trigger="resize">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-close-button="{{ demoCtrl.closeFromModel }}"
tooltip-template="a tooltip text"
tooltip-hide-trigger="resize">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-template="a tooltip text"
tooltip-size="small">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-template="a tooltip text"
tooltip-size="large">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-template="a tooltip text"
tooltip-size="{{ demoCtrl.sizeFromModel }}">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-template="a tooltip text"
tooltip-speed="fast">
Tooltip
</span>
</div>
<div>
<span tooltips
tooltip-template="a tooltip text"
tooltip-speed="{{ demoCtrl.speedFromModel }}">
Tooltip
</span>
</div>
<div class="scroll-area">
<p>
<button tooltips
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Top</button>
</p>
<p>
<button tooltips
tooltip-side="left"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Left</button>
</p>
<p>
<button tooltips
tooltip-side="right"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Right</button>
</p>
<p>
<button tooltips
tooltip-side="bottom"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Bottom</button>
</p>
</div>
<div class="scroll-area-horizontal">
<button tooltips
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Top</button>
<button tooltips
tooltip-side="left"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Left</button>
<button tooltips
tooltip-side="right"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Right</button>
<button tooltips
tooltip-side="bottom"
tooltip-append-to-body="true"
tooltip-template="A tooltip with text">Tooltip Bottom</button>
</div>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="dist/angular-tooltips.js"></script>
<script type="text/javascript" src="demo/js/index.js"></script>
</body>
</html>
| mit |
OpenSmalltalk/vm | processors/ARM/gdb-8.3.1/bfd/cpu-tic80.c | 1537 | /* bfd back-end for TI TMS320C80 (MVP) support
Copyright (C) 1996-2019 Free Software Foundation, Inc.
Written by Fred Fish at Cygnus support ([email protected])
This file is part of BFD, the Binary File Descriptor library.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
const bfd_arch_info_type bfd_tic80_arch =
{
32, /* 32 bits in a word */
32, /* 32 bits in an address */
8, /* 8 bits in a byte */
bfd_arch_tic80, /* bfd_architecture enum */
0, /* only 1 machine */
"tic80", /* architecture name */
"tic80", /* printable name */
2, /* section alignment power */
TRUE, /* default machine for architecture */
bfd_default_compatible,
bfd_default_scan,
bfd_arch_default_fill,
NULL, /* Pointer to next in chain */
};
| mit |
hansbonini/cloud9-magento | www/app/code/core/Mage/Cms/controllers/IndexController.php | 3373 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Cms
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Cms index controller
*
* @category Mage
* @package Mage_Cms
* @author Magento Core Team <[email protected]>
*/
class Mage_Cms_IndexController extends Mage_Core_Controller_Front_Action
{
/**
* Renders CMS Home page
*
* @param string $coreRoute
*/
public function indexAction($coreRoute = null)
{
$pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_HOME_PAGE);
if (!Mage::helper('cms/page')->renderPage($this, $pageId)) {
$this->_forward('defaultIndex');
}
}
/**
* Default index action (with 404 Not Found headers)
* Used if default page don't configure or available
*
*/
public function defaultIndexAction()
{
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$this->loadLayout();
$this->renderLayout();
}
/**
* Render CMS 404 Not found page
*
* @param string $coreRoute
*/
public function noRouteAction($coreRoute = null)
{
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE);
if (!Mage::helper('cms/page')->renderPage($this, $pageId)) {
$this->_forward('defaultNoRoute');
}
}
/**
* Default no route page action
* Used if no route page don't configure or available
*
*/
public function defaultNoRouteAction()
{
$this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
$this->getResponse()->setHeader('Status','404 File not found');
$this->loadLayout();
$this->renderLayout();
}
/**
* Render Disable cookies page
*
*/
public function noCookiesAction()
{
$pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_COOKIES_PAGE);
if (!Mage::helper('cms/page')->renderPage($this, $pageId)) {
$this->_forward('defaultNoCookies');;
}
}
/**
* Default no cookies page action
* Used if no cookies page don't configure or available
*
*/
public function defaultNoCookiesAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
| mit |
raymonddavis/Angular-SailsJs-SocketIo | web/node_modules/@angular/cli/blueprints/class/index.js | 2492 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const app_utils_1 = require("../../utilities/app-utils");
const dynamic_path_parser_1 = require("../../utilities/dynamic-path-parser");
const config_1 = require("../../models/config");
const stringUtils = require('ember-cli-string-utils');
const Blueprint = require('../../ember-cli/lib/models/blueprint');
const getFiles = Blueprint.prototype.files;
exports.default = Blueprint.extend({
name: 'class',
description: '',
aliases: ['cl'],
availableOptions: [
{
name: 'spec',
type: Boolean,
description: 'Specifies if a spec file is generated.'
},
{
name: 'app',
type: String,
aliases: ['a'],
description: 'Specifies app name to use.'
}
],
normalizeEntityName: function (entityName) {
const appConfig = app_utils_1.getAppFromConfig(this.options.app);
const parsedPath = dynamic_path_parser_1.dynamicPathParser(this.project, entityName.split('.')[0], appConfig);
this.dynamicPath = parsedPath;
return parsedPath.name;
},
locals: function (options) {
const rawName = options.args[1];
const nameParts = rawName.split('.')
.filter(part => part.length !== 0);
const classType = nameParts[1];
this.fileName = stringUtils.dasherize(options.entity.name);
if (classType) {
this.fileName += '.' + classType.toLowerCase();
}
options.spec = options.spec !== undefined ?
options.spec : config_1.CliConfig.getValue('defaults.class.spec');
return {
dynamicPath: this.dynamicPath.dir,
flat: options.flat,
fileName: this.fileName
};
},
files: function () {
let fileList = getFiles.call(this);
if (this.options && !this.options.spec) {
fileList = fileList.filter(p => p.indexOf('__name__.spec.ts') < 0);
}
return fileList;
},
fileMapTokens: function () {
// Return custom template variables here.
return {
__path__: () => {
this.generatePath = this.dynamicPath.dir;
return this.generatePath;
},
__name__: () => {
return this.fileName;
}
};
}
});
//# sourceMappingURL=/users/hans/sources/angular-cli/blueprints/class/index.js.map | mit |
viral810/ngSimpleCMS | web/bundles/sunraangular/js/angular/angular-1.3.3/docs/partials/api/ngAnimate/provider/$animateProvider.html | 1446 | <a href='https://github.com/angular/angular.js/edit/v1.3.x/src/ngAnimate/animate.js?message=docs($animateProvider)%3A%20describe%20your%20change...#L394' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.3.3/src/ngAnimate/animate.js#L394' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">$animateProvider</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
<a href="api/ngAnimate/service/$animate">- $animate</a>
</li>
<li>
- provider in module <a href="api/ngAnimate">ngAnimate</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>The <code>$animateProvider</code> allows developers to register JavaScript animation event handlers directly inside of a module.
When an animation is triggered, the $animate service will query the $animate service to find any animations that match
the provided name value.</p>
<p>Requires the <a href="api/ngAnimate"><code>ngAnimate</code></a> module to be installed.</p>
<p>Please visit the <a href="api/ngAnimate"><code>ngAnimate</code></a> module overview page learn more about how to use animations in your application.</p>
</div>
<div>
</div>
| mit |
djsedulous/namecoind | libs/boost_1_50_0/libs/icl/doc/html/boost/icl/interval_base_map/on_codomain_model_Type__id510081.html | 8211 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template on_codomain_model<Type, true></title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.74.0">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Icl">
<link rel="up" href="../interval_base_map.html#id1063321" title="Description">
<link rel="prev" href="on_codomain_model_Type__id510019.html" title="Struct template on_codomain_model<Type, false>">
<link rel="next" href="on_definedness_Type__fa_id510147.html" title="Struct template on_definedness<Type, false>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="on_codomain_model_Type__id510019.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../interval_base_map.html#id1063321"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="on_definedness_Type__fa_id510147.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry" lang="en">
<a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template on_codomain_model<Type, true></span></h2>
<p>boost::icl::interval_base_map::on_codomain_model<Type, true></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../header/boost/icl/interval_base_map_hpp.html" title="Header <boost/icl/interval_base_map.hpp>">boost/icl/interval_base_map.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Type<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="on_codomain_model_Type__id510081.html" title="Struct template on_codomain_model<Type, true>">on_codomain_model</a><span class="special"><</span><span class="identifier">Type</span><span class="special">,</span> <span class="keyword">true</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">Type</span><span class="special">::</span><span class="identifier">interval_type</span> <a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081.interval_type"></a><span class="identifier">interval_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">Type</span><span class="special">::</span><span class="identifier">codomain_type</span> <a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081.codomain_type"></a><span class="identifier">codomain_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">Type</span><span class="special">::</span><span class="identifier">segment_type</span> <a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081.segment_type"></a><span class="identifier">segment_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">Type</span><span class="special">::</span><span class="identifier">codomain_combine</span> <a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081.codomain_combine"></a><span class="identifier">codomain_combine</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">Type</span><span class="special">::</span><span class="identifier">inverse_codomain_intersect</span> <a name="boost.icl.interval_base_map.on_codomain_model_Type,_id510081.inverse_codomain_intersect"></a><span class="identifier">inverse_codomain_intersect</span><span class="special">;</span>
<span class="comment">// <a class="link" href="on_codomain_model_Type__id510081.html#id510119-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="on_codomain_model_Type__id510081.html#id510121-bb"><span class="identifier">add</span></a><span class="special">(</span><span class="identifier">Type</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">interval_type</span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">codomain_type</span> <span class="special">&</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">codomain_type</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1" lang="en">
<a name="id1069226"></a><h2>Description</h2>
<div class="refsect2" lang="en">
<a name="id1069229"></a><h3>
<a name="id510119-bb"></a><code class="computeroutput">on_codomain_model</code> public static functions</h3>
<div class="orderedlist"><ol type="1"><li><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="id510121-bb"></a><span class="identifier">add</span><span class="special">(</span><span class="identifier">Type</span> <span class="special">&</span> intersection<span class="special">,</span> <span class="identifier">interval_type</span> <span class="special">&</span> common_interval<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">codomain_type</span> <span class="special">&</span> flip_value<span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">codomain_type</span> <span class="special">&</span> co_value<span class="special">)</span><span class="special">;</span></pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 -2010 Joachim Faulhaber<br>Copyright © 1999 -2006 Cortex Software GmbH<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="on_codomain_model_Type__id510019.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../interval_base_map.html#id1063321"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="on_definedness_Type__fa_id510147.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
drBenway/siteResearch | vendor/phpunit/dbunit/PHPUnit/Extensions/Database/Operation/Composite_1.php | 3983 | <?php
/**
* PHPUnit
*
* Copyright (c) 2002-2014, Sebastian Bergmann <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package DbUnit
* @author Mike Lively <[email protected]>
* @copyright 2002-2014 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since File available since Release 1.0.0
*/
/**
* This class facilitates combining database operations. To create a composite
* operation pass an array of classes that implement
* PHPUnit_Extensions_Database_Operation_IDatabaseOperation and they will be
* executed in that order against all data sets.
*
* @package DbUnit
* @author Mike Lively <[email protected]>
* @copyright 2010-2014 Mike Lively <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @version Release: @package_version@
* @link http://www.phpunit.de/
* @since Class available since Release 1.0.0
*/
class PHPUnit_Extensions_Database_Operation_Composite implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation
{
/**
* @var array
*/
protected $operations = array();
/**
* Creates a composite operation.
*
* @param array $operations
*/
public function __construct(Array $operations)
{
foreach ($operations as $operation) {
if ($operation instanceof PHPUnit_Extensions_Database_Operation_IDatabaseOperation) {
$this->operations[] = $operation;
} else {
throw new InvalidArgumentException("Only database operation instances can be passed to a composite database operation.");
}
}
}
public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet)
{
try {
foreach ($this->operations as $operation) {
/* @var $operation PHPUnit_Extensions_Database_Operation_IDatabaseOperation */
$operation->execute($connection, $dataSet);
}
} catch (PHPUnit_Extensions_Database_Operation_Exception $e) {
throw new PHPUnit_Extensions_Database_Operation_Exception("COMPOSITE[{$e->getOperation()}]", $e->getQuery(), $e->getArgs(), $e->getTable(), $e->getError());
}
}
}
| mit |
aabustamante/Semantic-UI-React | src/modules/Dimmer/index.d.ts | 49 | export { default, DimmerProps } from './Dimmer';
| mit |
dav009/peco | keyseq/ternary.go | 3295 | package keyseq
type TernaryTrie struct {
root TernaryNode
}
func NewTernaryTrie() *TernaryTrie {
return &TernaryTrie{}
}
func (t *TernaryTrie) Root() Node {
return &t.root
}
func (t *TernaryTrie) GetList(k KeyList) Node {
return Get(t, k)
}
func (t *TernaryTrie) Get(k Key) Node {
return Get(t, KeyList{k})
}
func (t *TernaryTrie) Put(k KeyList, v interface{}) Node {
return Put(t, k, v)
}
func (t *TernaryTrie) Size() int {
count := 0
EachDepth(t, func(Node) bool {
count++
return true
})
return count
}
func (t *TernaryTrie) Balance() {
EachDepth(t, func(n Node) bool {
n.(*TernaryNode).Balance()
return true
})
t.root.Balance()
}
type TernaryNode struct {
label Key
firstChild *TernaryNode
low, high *TernaryNode
value interface{}
}
func NewTernaryNode(l Key) *TernaryNode {
return &TernaryNode{label: l}
}
func (n *TernaryNode) GetList(k KeyList) Node {
return n.Get(k[0])
}
func (n *TernaryNode) Get(k Key) Node {
curr := n.firstChild
for curr != nil {
switch k.Compare(curr.label) {
case 0: // equal
return curr
case -1: // less
curr = curr.low
default: //more
curr = curr.high
}
}
return nil
}
func (n *TernaryNode) Dig(k Key) (node Node, isnew bool) {
curr := n.firstChild
if curr == nil {
n.firstChild = NewTernaryNode(k)
return n.firstChild, true
}
for {
switch k.Compare(curr.label) {
case 0:
return curr, false
case -1:
if curr.low == nil {
curr.low = NewTernaryNode(k)
return curr.low, true
}
curr = curr.low
default:
if curr.high == nil {
curr.high = NewTernaryNode(k)
return curr.high, true
}
curr = curr.high
}
}
}
func (n *TernaryNode) FirstChild() *TernaryNode {
return n.firstChild
}
func (n *TernaryNode) HasChildren() bool {
return n.firstChild != nil
}
func (n *TernaryNode) Size() int {
if n.firstChild == nil {
return 0
}
count := 0
n.Each(func(Node) bool {
count++
return true
})
return count
}
func (n *TernaryNode) Each(proc func(Node) bool) {
var f func(*TernaryNode) bool
f = func(n *TernaryNode) bool {
if n != nil {
if !f(n.low) || !proc(n) || !f(n.high) {
return false
}
}
return true
}
f(n.firstChild)
}
func (n *TernaryNode) RemoveAll() {
n.firstChild = nil
}
func (n *TernaryNode) Label() Key {
return n.label
}
func (n *TernaryNode) Value() interface{} {
return n.value
}
func (n *TernaryNode) SetValue(v interface{}) {
n.value = v
}
func (n *TernaryNode) children() []*TernaryNode {
children := make([]*TernaryNode, n.Size())
if n.firstChild == nil {
return children
}
idx := 0
n.Each(func(child Node) bool {
children[idx] = child.(*TernaryNode)
idx++
return true
})
return children
}
func (n *TernaryNode) Balance() {
if n.firstChild == nil {
return
}
children := n.children()
for _, child := range children {
child.low = nil
child.high = nil
}
n.firstChild = balance(children, 0, len(children))
}
func balance(nodes []*TernaryNode, s, e int) *TernaryNode {
count := e - s
if count <= 0 {
return nil
} else if count == 1 {
return nodes[s]
} else if count == 2 {
nodes[s].high = nodes[s+1]
return nodes[s]
} else {
mid := (s + e) / 2
n := nodes[mid]
n.low = balance(nodes, s, mid)
n.high = balance(nodes, mid+1, e)
return n
}
}
| mit |
JonDouglas/XamarinComponents | XPlat/DropboxCoreApi/iOS/samples/DropboxCoreApiSample/DropboxCoreApiSample/TextViewController.cs | 3244 | using System;
using System.IO;
using Foundation;
using UIKit;
using CoreGraphics;
using Dropbox.CoreApi.iOS;
namespace DropboxCoreApiSample
{
public partial class TextViewController : UIViewController
{
// A TextField with Placeholder
CustomUITextView textView;
RestClient restClient;
string filename;
public TextViewController ()
{
View.BackgroundColor = UIColor.White;
// Will handle the save to Dropbox process
var btnSave = new UIBarButtonItem ("Save", UIBarButtonItemStyle.Plain, WriteFile);
btnSave.Enabled = false;
// Create the TextField with a Placeholder
textView = new CustomUITextView (CGRect.Empty, "Type something nice!");
textView.TranslatesAutoresizingMaskIntoConstraints = false;
// If the user has written something, you can save the file
textView.Changed += (sender, e) => btnSave.Enabled = textView.Text.Length != 0;
// Rest client that will handle the file upload
restClient = new RestClient (Session.SharedSession);
// Once the file is on Dropbox, notify the user
restClient.FileUploaded += (sender, e) => {
new UIAlertView ("Saved on Dropbox", "The file was uploaded to Dropbox correctly", null, "OK", null).Show ();
#if __UNIFIED__
NavigationController.PopViewController (true);
#else
NavigationController.PopViewControllerAnimated (true);
#endif
};
// Handle if something went wrong with the upload of the file
restClient.LoadFileFailed += (sender, e) => {
// Try to upload the file again
var alertView = new UIAlertView ("Hmm...", "Something went wrong when trying to save the file on Dropbox...", null, "Not now", new [] { "Try Again" });
alertView.Clicked += (avSender, avE) => {
if (avE.ButtonIndex == 1)
restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, Path.GetTempPath () + filename);
};
alertView.Show ();
};
// Add the view with its constraints
View.Add (textView);
NavigationItem.RightBarButtonItem = btnSave;
AddConstraints ();
}
void AddConstraints ()
{
var views = new NSDictionary ("textView", textView);
View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-0-[textView]-0-|", 0, null, views));
View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-0-[textView]-0-|", 0, null, views));
}
// Process to save the file on Dropbox
void WriteFile (object sender, EventArgs e)
{
// Notify that the user has ended typing
textView.EndEditing (true);
// Ask for a name to the file
var alertView = new UIAlertView ("Save to Dropbox", "Enter a name for the file", null, "Cancel", new [] { "Save" });
alertView.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alertView.Clicked += (avSender, avE) => {
// Once we have the name, we need to save the file locally first and then upload it to Dropbox
if (avE.ButtonIndex == 1) {
filename = alertView.GetTextField (0).Text + ".txt";
var fullPath = Path.GetTempPath () + filename;
// Write the file locally
File.WriteAllText (fullPath, textView.Text);
// Now upload it to Dropbox
restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, fullPath);
}
};
alertView.Show ();
}
}
}
| mit |
adilmughal/OpenLiveWriter | src/managed/OpenLiveWriter.PostEditor/PostPropertyEditing/PostPropertiesBandControl.cs | 13831 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor.PostPropertyEditing
{
/*
* TODO
* Bugs:
- Visibility is all screwed up!!
- Position of page-relevant labels vs. controls in dialog
* Putting focus in a textbox that has a cue banner, causes dirty flag to be marked
- Space should trigger View All
- F2 during page context shows too many labels
- Label visibility not staying in sync with control
- Unchecking publish date in dialog doesn't set cue banner in band
- Activate main window when dialog is dismissed
- Some labels not localized
- Labels do not have mnemonics
- Clicking on View All should restore a visible but minimized dialog
* Horizontal scrollbar sometimes flickers on
- Trackback detailed label
* Dropdown for Page Parent combo is not the right width
* Each Page Parent combo makes its own delayed request
- Tags control should share leftover space with category control
x Properties dialog should hide and come back
*
* Questions:
* Should Enter dismiss the properties dialog?
* Should properties dialog scroll state be remembered between views?
*/
public partial class PostPropertiesBandControl : UserControl, IBlogPostEditor, IRtlAware, INewCategoryContext
{
private Blog _targetBlog;
private IBlogClientOptions _clientOptions;
private const int COL_CATEGORY = 0;
private const int COL_TAGS = 1;
private const int COL_DATE = 2;
private const int COL_PAGEPARENTLABEL = 3;
private const int COL_PAGEPARENT = 4;
private const int COL_PAGEORDERLABEL = 5;
private const int COL_PAGEORDER = 6;
private const int COL_FILLER = 7;
private const int COL_VIEWALL = 8;
private readonly PostPropertiesForm postPropertiesForm;
private readonly List<PropertyField> fields = new List<PropertyField>();
private readonly SharedPropertiesController controller;
private readonly CategoryContext categoryContext;
public PostPropertiesBandControl(CommandManager commandManager)
{
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
InitializeComponent();
categoryContext = new CategoryContext();
controller = new SharedPropertiesController(this, null, categoryDropDown,
null, textTags, labelPageOrder, textPageOrder, labelPageParent, comboPageParent, null,
datePublishDate, fields, categoryContext);
SimpleTextEditorCommandHelper.UseNativeBehaviors(commandManager,
textTags, textPageOrder);
postPropertiesForm = new PostPropertiesForm(commandManager, categoryContext);
if (components == null)
components = new Container();
components.Add(postPropertiesForm);
postPropertiesForm.Synchronize(controller);
commandManager.Add(CommandId.PostProperties, PostProperties_Execute);
commandManager.Add(CommandId.ShowCategoryPopup, ShowCategoryPopup_Execute);
linkViewAll.KeyDown += (sender, args) =>
{
if (args.KeyValue == ' ')
linkViewAll_LinkClicked(sender, new LinkLabelLinkClickedEventArgs(null));
};
// WinLive 180287: We don't want to show or use mnemonics on labels in the post properties band because
// they can steal focus from the canvas.
linkViewAll.Text = TextHelper.StripAmpersands(Res.Get(StringId.ViewAll));
linkViewAll.UseMnemonic = false;
labelPageParent.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageParent));
labelPageParent.UseMnemonic = false;
labelPageOrder.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageOrder));
labelPageOrder.UseMnemonic = false;
}
private void ShowCategoryPopup_Execute(object sender, EventArgs e)
{
if (postPropertiesForm.Visible)
postPropertiesForm.DisplayCategoryForm();
else
categoryDropDown.DisplayCategoryForm();
}
protected override void OnLoad(EventArgs args)
{
base.OnLoad(args);
FixCategoryDropDown();
}
private void FixCategoryDropDown()
{
// Exactly align the sizes of the category control and the publish datetime picker control
int nonItemHeight = categoryDropDown.Height - categoryDropDown.ItemHeight;
categoryDropDown.ItemHeight = datePublishDate.Height - nonItemHeight;
categoryDropDown.Height = datePublishDate.Height;
datePublishDate.LocationChanged += delegate
{
// Exactly align the vertical position of the category control and the publish datetime picker control
categoryDropDown.Anchor = categoryDropDown.Anchor | AnchorStyles.Top;
Padding margin = categoryDropDown.Margin;
margin.Top = datePublishDate.Top;
categoryDropDown.Margin = margin;
};
}
private void PostProperties_Execute(object sender, EventArgs e)
{
if (!Visible)
return;
if (postPropertiesForm.Visible)
postPropertiesForm.Hide();
else
postPropertiesForm.Show(FindForm());
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
Invalidate();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Without the height/width checks, minimizing and restoring causes painting to blow up
if (!SystemInformation.HighContrast && table.Height > 0 && table.Width > 0 && panelShadow.Height > 0 && panelShadow.Width > 0)
{
using (
Brush brush = new LinearGradientBrush(table.Bounds, Color.FromArgb(0xDC, 0xE7, 0xF5), Color.White,
LinearGradientMode.Vertical))
e.Graphics.FillRectangle(brush, table.Bounds);
using (
Brush brush = new LinearGradientBrush(panelShadow.Bounds, Color.FromArgb(208, 208, 208), Color.White,
LinearGradientMode.Vertical))
e.Graphics.FillRectangle(brush, panelShadow.Bounds);
}
else
{
e.Graphics.Clear(SystemColors.Window);
}
}
private bool categoryVisible = true;
private bool CategoryVisible
{
set
{
table.ColumnStyles[COL_CATEGORY].SizeType = value ? SizeType.Percent : SizeType.AutoSize;
categoryDropDown.Visible = categoryVisible = value;
ManageFillerVisibility();
}
}
private bool tagsVisible = true;
private bool TagsVisible
{
set
{
table.ColumnStyles[COL_TAGS].SizeType = value ? SizeType.Percent : SizeType.AutoSize;
textTags.Visible = tagsVisible = value;
ManageFillerVisibility();
}
}
private void ManageFillerVisibility()
{
bool shouldShow = !categoryVisible && !tagsVisible;
table.ColumnStyles[COL_FILLER].SizeType = shouldShow ? SizeType.Percent : SizeType.AutoSize;
}
private IBlogPostEditingContext _editorContext;
public void Initialize(IBlogPostEditingContext editorContext, IBlogClientOptions clientOptions)
{
_editorContext = editorContext;
_clientOptions = clientOptions;
controller.Initialize(editorContext, clientOptions);
((IBlogPostEditor)postPropertiesForm).Initialize(editorContext, clientOptions);
ManageLayout();
}
private bool IsPage
{
get { return _editorContext != null && _editorContext.BlogPost != null ? _editorContext.BlogPost.IsPage : false; }
}
public void OnBlogChanged(Blog newBlog)
{
_clientOptions = newBlog.ClientOptions;
_targetBlog = newBlog;
controller.OnBlogChanged(newBlog);
((IBlogPostEditor)postPropertiesForm).OnBlogChanged(newBlog);
ManageLayout();
}
public void OnBlogSettingsChanged(bool templateChanged)
{
controller.OnBlogSettingsChanged(templateChanged);
((IBlogPostEditor)postPropertiesForm).OnBlogSettingsChanged(templateChanged);
ManageLayout();
}
private void ManageLayout()
{
if (IsPage)
{
bool showViewAll = _clientOptions.SupportsCommentPolicy
|| _clientOptions.SupportsPingPolicy
|| _clientOptions.SupportsAuthor
|| _clientOptions.SupportsSlug
|| _clientOptions.SupportsPassword;
linkViewAll.Visible = showViewAll;
CategoryVisible = false;
TagsVisible = false;
Visible = showViewAll || _clientOptions.SupportsPageParent || _clientOptions.SupportsPageOrder;
}
else
{
bool showViewAll = _clientOptions.SupportsCommentPolicy
|| _clientOptions.SupportsPingPolicy
|| _clientOptions.SupportsAuthor
|| _clientOptions.SupportsSlug
|| _clientOptions.SupportsPassword
|| _clientOptions.SupportsExcerpt
|| _clientOptions.SupportsTrackbacks;
bool showTags = (_clientOptions.SupportsKeywords && (_clientOptions.KeywordsAsTags || _clientOptions.SupportsGetKeywords));
Visible = showViewAll
|| _clientOptions.SupportsCustomDate
|| showTags
|| _clientOptions.SupportsCategories;
CategoryVisible = _clientOptions.SupportsCategories;
TagsVisible = showTags;
linkViewAll.Visible = showViewAll;
}
}
public bool IsDirty
{
get { return controller.IsDirty || ((IBlogPostEditor)postPropertiesForm).IsDirty; }
}
public bool HasKeywords
{
get { return postPropertiesForm.HasKeywords; }
}
public void SaveChanges(BlogPost post, BlogPostSaveOptions options)
{
controller.SaveChanges(post, options);
((IBlogPostEditor)postPropertiesForm).SaveChanges(post, options);
}
public bool ValidatePublish()
{
return controller.ValidatePublish();
}
public void OnPublishSucceeded(BlogPost blogPost, PostResult postResult)
{
controller.OnPublishSucceeded(blogPost, postResult);
((IBlogPostEditor)postPropertiesForm).OnPublishSucceeded(blogPost, postResult);
}
public void OnClosing(CancelEventArgs e)
{
controller.OnClosing(e);
((IBlogPostEditor)postPropertiesForm).OnClosing(e);
}
public void OnPostClosing(CancelEventArgs e)
{
controller.OnPostClosing(e);
((IBlogPostEditor)postPropertiesForm).OnPostClosing(e);
}
public void OnClosed()
{
controller.OnClosed();
((IBlogPostEditor)postPropertiesForm).OnClosed();
}
public void OnPostClosed()
{
controller.OnPostClosed();
((IBlogPostEditor)postPropertiesForm).OnPostClosed();
}
private void linkViewAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (!postPropertiesForm.Visible)
postPropertiesForm.Show(FindForm());
else
{
if (postPropertiesForm.WindowState == FormWindowState.Minimized)
postPropertiesForm.WindowState = FormWindowState.Normal;
postPropertiesForm.Activate();
}
}
void IRtlAware.Layout()
{
}
#region Implementation of INewCategoryContext
public void NewCategoryAdded(BlogPostCategory category)
{
controller.NewCategoryAdded(category);
}
#endregion
}
}
| mit |
spi-ke/Socialman | src/vendors/herrera-io/cli-app/src/tests/Herrera/Cli/Tests/Provider/ErrorHandlingServiceProviderTest.php | 828 | <?php
namespace Herrera\Cli\Tests\Provider;
use Herrera\Cli\Provider\ErrorHandlingServiceProvider;
use Herrera\PHPUnit\TestCase;
use Herrera\Service\Container;
class ErrorHandlingServiceProviderTest extends TestCase
{
public function testRegister()
{
$container = new Container();
$container->register(new ErrorHandlingServiceProvider());
$this->setExpectedException(
'ErrorException',
'Test error.'
);
trigger_error('Test error.', E_USER_ERROR);
}
public function testRegisterIgnored()
{
$container = new Container();
$container->register(new ErrorHandlingServiceProvider());
error_reporting(E_ALL ^ E_USER_NOTICE);
trigger_error('Test error.', E_USER_NOTICE);
$this->assertTrue(true);
}
}
| mit |
ALTELMA/OfficeEquipmentManager | application/libraries/PHPExcel/branches/v1.1.1/Build/build.php | 3220 | <?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2007 PHPExcel, Maarten Balliauw
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @copyright Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/gpl.txt GPL
*/
/**
* This file creates a build of PHPExcel
*/
// Starting build
echo date('H:i:s') . " Starting build...\n";
// Specify paths and files to include
$aFilesToInclude = array('../changelog.txt', '../install.txt', '../license.txt');
$aPathsToInclude = array('../Classes', '../Tests', '../Documentation');
// Resulting file
$strResultingFile = 'LatestBuild.zip';
// Create new ZIP file and open it for writing
echo date('H:i:s') . " Creating ZIP archive...\n";
$objZip = new ZipArchive();
// Try opening the ZIP file
if ($objZip->open($strResultingFile, ZIPARCHIVE::OVERWRITE) !== true) {
throw new Exeption("Could not open " . $strResultingFile . " for writing!");
}
// Add files to include
foreach ($aFilesToInclude as $strFile) {
echo date('H:i:s') . " Adding file $strFile\n";
$objZip->addFile($strFile, cleanFileName($strFile));
}
// Add paths to include
foreach ($aPathsToInclude as $strPath) {
addPathToZIP($strPath, $objZip);
}
// Set archive comment...
echo date('H:i:s') . " Set archive comment...\n";
$objZip->setArchiveComment('PHPExcel - http://www.codeplex.com/PHPExcel');
// Close file
echo date('H:i:s') . " Saving ZIP archive...\n";
$objZip->close();
// Finished build
echo date('H:i:s') . " Finished build!\n";
/**
* Add a specific path's files and folders to a ZIP object
*
* @param string $strPath Path to add
* @param ZipArchive $objZip ZipArchive object
*/
function addPathToZIP($strPath, $objZip) {
echo date('H:i:s') . " Adding path $strPath...\n";
$currentDir = opendir($strPath);
while ($strFile = readdir($currentDir)) {
if ($strFile != '.' && $strFile != '..') {
if (is_file($strPath . '/' . $strFile)) {
$objZip->addFile($strPath . '/' . $strFile, cleanFileName($strPath . '/' . $strFile));
} else if (is_dir($strPath . '/' . $strFile)) {
if (!eregi('.svn', $strFile)) {
addPathToZIP( ($strPath . '/' . $strFile), $objZip );
}
}
}
}
}
/**
* Cleanup a filename
*
* @param string $strFile Filename
* @return string Filename
*/
function cleanFileName($strFile) {
$strFile = str_replace('../', '', $strFile);
$strFile = str_replace('WINDOWS', '', $strFile);
while (eregi('//', $strFile)) {
$strFile = str_replace('//', '/', $strFile);
}
return $strFile;
} | mit |
gkalpak/angular | aio/content/examples/lazy-loading-ngmodules/src/app/app.component.html | 342 | <!-- #docplaster -->
<!-- #docregion app-component-template -->
<h1>
{{title}}
</h1>
<button type="button" routerLink="/customers">Customers</button>
<button type="button" routerLink="/orders">Orders</button>
<button type="button" routerLink="">Home</button>
<router-outlet></router-outlet>
<!-- #enddocregion app-component-template -->
| mit |
nchoudhary-ishir/InnovativeSolutionBuyerApp2 | src/app/catalog/templates/category.list.tpl.html | 756 | <article id="CategoryList">
<h3 ng-if="categorylist.length > 0" class="page-header">
{{categorylist.length > 1 ? 'Categories' : 'Category'}}
</h3>
<div class="category-list row">
<div class="category-list-item col-md-3" ng-repeat="category in categorylist">
<div class="thumbnail" ui-sref="catalog.category({categoryid: category.ID})">
<figure ng-if="category.xp.image">
<img class="img-responsive" ng-src="{{category.xp.image.URL}}" alt="Category Image">
</figure>
<div class="caption">
<h4 class="text-center">{{category.Name || category.ID}}</h4>
</div>
</div>
</div>
</div>
</article> | mit |
dr-em/BotBuilder | CSharp/Library/Microsoft.Bot.Connector/ConnectorAPI/Models/AttachmentView.cs | 1269 | // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Bot.Connector
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
/// <summary>
/// Attachment View name and size
/// </summary>
public partial class AttachmentView
{
/// <summary>
/// Initializes a new instance of the AttachmentView class.
/// </summary>
public AttachmentView() { }
/// <summary>
/// Initializes a new instance of the AttachmentView class.
/// </summary>
public AttachmentView(string viewId = default(string), int? size = default(int?))
{
ViewId = viewId;
Size = size;
}
/// <summary>
/// content type of the attachmnet
/// </summary>
[JsonProperty(PropertyName = "viewId")]
public string ViewId { get; set; }
/// <summary>
/// Name of the attachment
/// </summary>
[JsonProperty(PropertyName = "size")]
public int? Size { get; set; }
}
}
| mit |
viral810/ngSimpleCMS | web/bundles/sunraangular/js/angular/angular-1.3.3/docs/partials/api/ng/filter/lowercase.html | 1047 | <a href='https://github.com/angular/angular.js/edit/v1.3.x/src/ng/filter/filters.js?message=docs(lowercase)%3A%20describe%20your%20change...#L529' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.3.3/src/ng/filter/filters.js#L529' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">lowercase</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- filter in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Converts string to lowercase.</p>
</div>
<div>
<h2>Usage</h2>
<h3>In HTML Template Binding</h3>
<pre><code>{{ lowercase_expression | lowercase}}</code></pre>
<h3>In JavaScript</h3>
<pre><code>$filter('lowercase')()</code></pre>
</div>
| mit |
slattery/Haraka | tests/plugins/auth/auth_vpopmaild.js | 2773 | 'use strict';
var path = require('path');
var fixtures = require('haraka-test-fixtures');
var Connection = fixtures.connection;
var Plugin = fixtures.plugin;
var _set_up = function(done) {
this.backup = {};
// needed for tests
this.plugin = new Plugin('auth/auth_vpopmaild');
this.plugin.inherits('auth/auth_base');
// reset the config/root_path
this.plugin.config.root_path = path.resolve(__dirname, '../../../config');
this.plugin.cfg = this.plugin.config.get('auth_vpopmaild.ini');
this.connection = Connection.createConnection();
this.connection.capabilities=null;
done();
};
exports.hook_capabilities = {
setUp : _set_up,
'no TLS': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.equal(null, this.connection.capabilities);
test.done();
}.bind(this);
this.plugin.hook_capabilities(cb, this.connection);
},
'with TLS': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.ok(this.connection.capabilities.length);
// console.log(this.connection.capabilities);
test.done();
}.bind(this);
this.connection.using_tls=true;
this.connection.capabilities=[];
this.plugin.hook_capabilities(cb, this.connection);
},
'with TLS, sysadmin': function (test) {
var cb = function (rc, msg) {
test.expect(3);
test.equal(undefined, rc);
test.equal(undefined, msg);
test.ok(this.connection.capabilities.length);
// console.log(this.connection.capabilities);
test.done();
}.bind(this);
this.connection.using_tls=true;
this.connection.capabilities=[];
this.plugin.hook_capabilities(cb, this.connection);
},
};
exports.get_vpopmaild_socket = {
setUp : _set_up,
'any': function (test) {
test.expect(1);
var socket = this.plugin.get_vpopmaild_socket('[email protected]');
// console.log(socket);
test.ok(socket);
socket.end();
test.done();
}
};
exports.get_plain_passwd = {
setUp : _set_up,
'[email protected]': function (test) {
var cb = function (pass) {
test.expect(1);
test.ok(pass);
test.done();
};
if (this.plugin.cfg['example.com'].sysadmin) {
this.plugin.get_plain_passwd('[email protected]', cb);
}
else {
test.expect(0);
test.done();
}
}
};
| mit |
mavasani/roslyn | src/Compilers/CSharp/Portable/Symbols/Symbol.cs | 68726 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The base class for all symbols (namespaces, classes, method, parameters, etc.) that are
/// exposed by the compiler.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal abstract partial class Symbol : ISymbolInternal, IFormattable
{
private ISymbol _lazyISymbol;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Changes to the public interface of this class should remain synchronized with the VB version of Symbol.
// Do not make any changes to the public interface without making the corresponding change
// to the VB version.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// <summary>
/// True if this Symbol should be completed by calling ForceComplete.
/// Intuitively, true for source entities (from any compilation).
/// </summary>
internal virtual bool RequiresCompletion
{
get { return false; }
}
internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
// must be overridden by source symbols, no-op for other symbols
Debug.Assert(!this.RequiresCompletion);
}
internal virtual bool HasComplete(CompletionPart part)
{
// must be overridden by source symbols, no-op for other symbols
Debug.Assert(!this.RequiresCompletion);
return true;
}
/// <summary>
/// Gets the name of this symbol. Symbols without a name return the empty string; null is
/// never returned.
/// </summary>
public virtual string Name
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets the name of a symbol as it appears in metadata. Most of the time, this
/// is the same as the Name property, with the following exceptions:
/// 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that
/// indicates the number of type parameters (it does not include, however, names of
/// containing types or namespaces).
/// 2) The metadata name of explicit interface names have spaces removed, compared to
/// the name property.
/// </summary>
public virtual string MetadataName
{
get
{
return this.Name;
}
}
/// <summary>
/// Gets the token for this symbol as it appears in metadata. Most of the time this is 0,
/// as it is when the symbol is not loaded from metadata.
/// </summary>
public virtual int MetadataToken => 0;
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public abstract SymbolKind Kind { get; }
/// <summary>
/// Get the symbol that logically contains this symbol.
/// </summary>
public abstract Symbol ContainingSymbol { get; }
/// <summary>
/// Returns the nearest lexically enclosing type, or null if there is none.
/// </summary>
public virtual NamedTypeSymbol ContainingType
{
get
{
Symbol container = this.ContainingSymbol;
NamedTypeSymbol containerAsType = container as NamedTypeSymbol;
// NOTE: container could be null, so we do not check
// whether containerAsType is not null, but
// instead check if it did not change after
// the cast.
if ((object)containerAsType == (object)container)
{
// this should be relatively uncommon
// most symbols that may be contained in a type
// know their containing type and can override ContainingType
// with a more precise implementation
return containerAsType;
}
// this is recursive, but recursion should be very short
// before we reach symbol that definitely knows its containing type.
return container.ContainingType;
}
}
/// <summary>
/// Gets the nearest enclosing namespace for this namespace or type. For a nested type,
/// returns the namespace that contains its container.
/// </summary>
public virtual NamespaceSymbol ContainingNamespace
{
get
{
for (var container = this.ContainingSymbol; (object)container != null; container = container.ContainingSymbol)
{
var ns = container as NamespaceSymbol;
if ((object)ns != null)
{
return ns;
}
}
return null;
}
}
/// <summary>
/// Returns the assembly containing this symbol. If this symbol is shared across multiple
/// assemblies, or doesn't belong to an assembly, returns null.
/// </summary>
public virtual AssemblySymbol ContainingAssembly
{
get
{
// Default implementation gets the containers assembly.
var container = this.ContainingSymbol;
return (object)container != null ? container.ContainingAssembly : null;
}
}
/// <summary>
/// For a source assembly, the associated compilation.
/// For any other assembly, null.
/// For a source module, the DeclaringCompilation of the associated source assembly.
/// For any other module, null.
/// For any other symbol, the DeclaringCompilation of the associated module.
/// </summary>
/// <remarks>
/// We're going through the containing module, rather than the containing assembly,
/// because of /addmodule (symbols in such modules should return null).
///
/// Remarks, not "ContainingCompilation" because it isn't transitive.
/// </remarks>
internal virtual CSharpCompilation DeclaringCompilation
{
get
{
switch (this.Kind)
{
case SymbolKind.ErrorType:
return null;
case SymbolKind.Assembly:
Debug.Assert(!(this is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation");
return null;
case SymbolKind.NetModule:
Debug.Assert(!(this is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation");
return null;
}
var sourceModuleSymbol = this.ContainingModule as SourceModuleSymbol;
return (object)sourceModuleSymbol == null ? null : sourceModuleSymbol.DeclaringCompilation;
}
}
Compilation ISymbolInternal.DeclaringCompilation
=> DeclaringCompilation;
string ISymbolInternal.Name => this.Name;
string ISymbolInternal.MetadataName => this.MetadataName;
ISymbolInternal ISymbolInternal.ContainingSymbol => this.ContainingSymbol;
IModuleSymbolInternal ISymbolInternal.ContainingModule => this.ContainingModule;
IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => this.ContainingAssembly;
ImmutableArray<Location> ISymbolInternal.Locations => this.Locations;
INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => this.ContainingNamespace;
bool ISymbolInternal.IsImplicitlyDeclared => this.IsImplicitlyDeclared;
INamedTypeSymbolInternal ISymbolInternal.ContainingType
{
get
{
return this.ContainingType;
}
}
ISymbol ISymbolInternal.GetISymbol() => this.ISymbol;
/// <summary>
/// Returns the module containing this symbol. If this symbol is shared across multiple
/// modules, or doesn't belong to a module, returns null.
/// </summary>
internal virtual ModuleSymbol ContainingModule
{
get
{
// Default implementation gets the containers module.
var container = this.ContainingSymbol;
return (object)container != null ? container.ContainingModule : null;
}
}
/// <summary>
/// The index of this member in the containing symbol. This is an optional
/// property, implemented by anonymous type properties only, for comparing
/// symbols in flow analysis.
/// </summary>
/// <remarks>
/// Should this be used for tuple fields as well?
/// </remarks>
internal virtual int? MemberIndexOpt => null;
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
public Symbol OriginalDefinition
{
get
{
return OriginalSymbolDefinition;
}
}
protected virtual Symbol OriginalSymbolDefinition
{
get
{
return this;
}
}
/// <summary>
/// Returns true if this is the original definition of this symbol.
/// </summary>
public bool IsDefinition
{
get
{
return (object)this == (object)OriginalDefinition;
}
}
/// <summary>
/// <para>
/// Get a source location key for sorting. For performance, it's important that this
/// be able to be returned from a symbol without doing any additional allocations (even
/// if nothing is cached yet.)
/// </para>
/// <para>
/// Only (original) source symbols and namespaces that can be merged
/// need implement this function if they want to do so for efficiency.
/// </para>
/// </summary>
internal virtual LexicalSortKey GetLexicalSortKey()
{
var locations = this.Locations;
var declaringCompilation = this.DeclaringCompilation;
Debug.Assert(declaringCompilation != null); // require that it is a source symbol
return (locations.Length > 0) ? new LexicalSortKey(locations[0], declaringCompilation) : LexicalSortKey.NotInSource;
}
/// <summary>
/// Gets the locations where this symbol was originally defined, either in source or
/// metadata. Some symbols (for example, partial classes) may be defined in more than one
/// location.
/// </summary>
public abstract ImmutableArray<Location> Locations { get; }
/// <summary>
/// <para>
/// Get the syntax node(s) where this symbol was declared in source. Some symbols (for
/// example, partial classes) may be defined in more than one location. This property should
/// return one or more syntax nodes only if the symbol was declared in source code and also
/// was not implicitly declared (see the <see cref="IsImplicitlyDeclared"/> property).
/// </para>
/// <para>
/// Note that for namespace symbol, the declaring syntax might be declaring a nested
/// namespace. For example, the declaring syntax node for N1 in "namespace N1.N2 {...}" is
/// the entire <see cref="BaseNamespaceDeclarationSyntax"/> for N1.N2. For the global namespace, the declaring
/// syntax will be the <see cref="CompilationUnitSyntax"/>.
/// </para>
/// </summary>
/// <returns>
/// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or
/// was implicitly declared, returns an empty read-only array.
/// </returns>
/// <remarks>
/// To go the opposite direction (from syntax node to symbol), see <see
/// cref="CSharpSemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>.
/// </remarks>
public abstract ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get; }
/// <summary>
/// Helper for implementing <see cref="DeclaringSyntaxReferences"/> for derived classes that store a location but not a
/// <see cref="CSharpSyntaxNode"/> or <see cref="SyntaxReference"/>.
/// </summary>
internal static ImmutableArray<SyntaxReference> GetDeclaringSyntaxReferenceHelper<TNode>(ImmutableArray<Location> locations)
where TNode : CSharpSyntaxNode
{
if (locations.IsEmpty)
{
return ImmutableArray<SyntaxReference>.Empty;
}
ArrayBuilder<SyntaxReference> builder = ArrayBuilder<SyntaxReference>.GetInstance();
foreach (Location location in locations)
{
// Location may be null. See https://github.com/dotnet/roslyn/issues/28862.
if (location == null || !location.IsInSource)
{
continue;
}
if (location.SourceSpan.Length != 0)
{
SyntaxToken token = location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start);
if (token.Kind() != SyntaxKind.None)
{
CSharpSyntaxNode node = token.Parent.FirstAncestorOrSelf<TNode>();
if (node != null)
{
builder.Add(node.GetReference());
}
}
}
else
{
// Since the location we're interested in can't contain a token, we'll inspect the whole tree,
// pruning away branches that don't contain that location. We'll pick the narrowest node of the type
// we're looking for.
// eg: finding the ParameterSyntax from the empty location of a blank identifier
SyntaxNode parent = location.SourceTree.GetRoot();
SyntaxNode found = null;
foreach (var descendant in parent.DescendantNodesAndSelf(c => c.Location.SourceSpan.Contains(location.SourceSpan)))
{
if (descendant is TNode && descendant.Location.SourceSpan.Contains(location.SourceSpan))
{
found = descendant;
}
}
if (found is object)
{
builder.Add(found.GetReference());
}
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Get this accessibility that was declared on this symbol. For symbols that do not have
/// accessibility declared on them, returns <see cref="Accessibility.NotApplicable"/>.
/// </summary>
public abstract Accessibility DeclaredAccessibility { get; }
/// <summary>
/// Returns true if this symbol is "static"; i.e., declared with the <c>static</c> modifier or
/// implicitly static.
/// </summary>
public abstract bool IsStatic { get; }
/// <summary>
/// Returns true if this symbol is "virtual", has an implementation, and does not override a
/// base class member; i.e., declared with the <c>virtual</c> modifier. Does not return true for
/// members declared as abstract or override.
/// </summary>
public abstract bool IsVirtual { get; }
/// <summary>
/// Returns true if this symbol was declared to override a base class member; i.e., declared
/// with the <c>override</c> modifier. Still returns true if member was declared to override
/// something, but (erroneously) no member to override exists.
/// </summary>
/// <remarks>
/// Even for metadata symbols, <see cref="IsOverride"/> = true does not imply that <see cref="IMethodSymbol.OverriddenMethod"/> will
/// be non-null.
/// </remarks>
public abstract bool IsOverride { get; }
/// <summary>
/// Returns true if this symbol was declared as requiring an override; i.e., declared with
/// the <c>abstract</c> modifier. Also returns true on a type declared as "abstract", all
/// interface types, and members of interface types.
/// </summary>
public abstract bool IsAbstract { get; }
/// <summary>
/// Returns true if this symbol was declared to override a base class member and was also
/// sealed from further overriding; i.e., declared with the <c>sealed</c> modifier. Also set for
/// types that do not allow a derived class (declared with <c>sealed</c> or <c>static</c> or <c>struct</c>
/// or <c>enum</c> or <c>delegate</c>).
/// </summary>
public abstract bool IsSealed { get; }
/// <summary>
/// Returns true if this symbol has external implementation; i.e., declared with the
/// <c>extern</c> modifier.
/// </summary>
public abstract bool IsExtern { get; }
/// <summary>
/// Returns true if this symbol was automatically created by the compiler, and does not
/// have an explicit corresponding source code declaration.
///
/// This is intended for symbols that are ordinary symbols in the language sense,
/// and may be used by code, but that are simply declared implicitly rather than
/// with explicit language syntax.
///
/// Examples include (this list is not exhaustive):
/// the default constructor for a class or struct that is created if one is not provided,
/// the BeginInvoke/Invoke/EndInvoke methods for a delegate,
/// the generated backing field for an auto property or a field-like event,
/// the "this" parameter for non-static methods,
/// the "value" parameter for a property setter,
/// the parameters on indexer accessor methods (not on the indexer itself),
/// methods in anonymous types,
/// anonymous functions
/// </summary>
public virtual bool IsImplicitlyDeclared
{
get { return false; }
}
/// <summary>
/// Returns true if this symbol can be referenced by its name in code. Examples of symbols
/// that cannot be referenced by name are:
/// constructors, destructors, operators, explicit interface implementations,
/// accessor methods for properties and events, array types.
/// </summary>
public bool CanBeReferencedByName
{
get
{
switch (this.Kind)
{
case SymbolKind.Local:
case SymbolKind.Label:
case SymbolKind.Alias:
case SymbolKind.RangeVariable:
// never imported, and always references by name.
return true;
case SymbolKind.Namespace:
case SymbolKind.Field:
case SymbolKind.ErrorType:
case SymbolKind.Parameter:
case SymbolKind.TypeParameter:
case SymbolKind.Event:
break;
case SymbolKind.NamedType:
if (((NamedTypeSymbol)this).IsSubmissionClass)
{
return false;
}
break;
case SymbolKind.Property:
var property = (PropertySymbol)this;
if (property.IsIndexer || property.MustCallMethodsDirectly)
{
return false;
}
break;
case SymbolKind.Method:
var method = (MethodSymbol)this;
switch (method.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.ReducedExtension:
break;
case MethodKind.Destructor:
// You wouldn't think that destructors would be referenceable by name, but
// dev11 only prevents them from being invoked - they can still be assigned
// to delegates.
return true;
case MethodKind.DelegateInvoke:
return true;
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
if (!((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly())
{
return false;
}
break;
default:
return false;
}
break;
case SymbolKind.ArrayType:
case SymbolKind.PointerType:
case SymbolKind.FunctionPointerType:
case SymbolKind.Assembly:
case SymbolKind.DynamicType:
case SymbolKind.NetModule:
case SymbolKind.Discard:
return false;
default:
throw ExceptionUtilities.UnexpectedValue(this.Kind);
}
// This will eliminate backing fields for auto-props, explicit interface implementations,
// indexers, etc.
// See the comment on ContainsDroppedIdentifierCharacters for an explanation of why
// such names are not referenceable (or see DevDiv #14432).
return SyntaxFacts.IsValidIdentifier(this.Name) &&
!SyntaxFacts.ContainsDroppedIdentifierCharacters(this.Name);
}
}
/// <summary>
/// As an optimization, viability checking in the lookup code should use this property instead
/// of <see cref="CanBeReferencedByName"/>. The full name check will then be performed in the <see cref="CSharpSemanticModel"/>.
/// </summary>
/// <remarks>
/// This property exists purely for performance reasons.
/// </remarks>
internal bool CanBeReferencedByNameIgnoringIllegalCharacters
{
get
{
if (this.Kind == SymbolKind.Method)
{
var method = (MethodSymbol)this;
switch (method.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.DelegateInvoke:
case MethodKind.Destructor: // See comment in CanBeReferencedByName.
return true;
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
return ((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly();
default:
return false;
}
}
return true;
}
}
/// <summary>
/// Perform additional checks after the member has been
/// added to the member list of the containing type.
/// </summary>
internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
}
// Note: This is no public "IsNew". This is intentional, because new has no syntactic meaning.
// It serves only to remove a warning. Furthermore, it can not be inferred from
// metadata. For symbols defined in source, the modifiers in the syntax tree
// can be examined.
/// <summary>
/// Compare two symbol objects to see if they refer to the same symbol. You should always
/// use <see cref="operator =="/> and <see cref="operator !="/>, or the <see cref="Equals(object)"/> method, to compare two symbols for equality.
/// </summary>
public static bool operator ==(Symbol left, Symbol right)
{
//PERF: this function is often called with
// 1) left referencing same object as the right
// 2) right being null
// The code attempts to check for these conditions before
// resorting to .Equals
// the condition is expected to be folded when inlining "someSymbol == null"
if (right is null)
{
return left is null;
}
// this part is expected to disappear when inlining "someSymbol == null"
return (object)left == (object)right || right.Equals(left);
}
/// <summary>
/// Compare two symbol objects to see if they refer to the same symbol. You should always
/// use == and !=, or the Equals method, to compare two symbols for equality.
/// </summary>
public static bool operator !=(Symbol left, Symbol right)
{
//PERF: this function is often called with
// 1) left referencing same object as the right
// 2) right being null
// The code attempts to check for these conditions before
// resorting to .Equals
//
//NOTE: we do not implement this as !(left == right)
// since that sometimes results in a worse code
// the condition is expected to be folded when inlining "someSymbol != null"
if (right is null)
{
return left is object;
}
// this part is expected to disappear when inlining "someSymbol != null"
return (object)left != (object)right && !right.Equals(left);
}
public sealed override bool Equals(object obj)
{
return this.Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind);
}
public bool Equals(Symbol other)
{
return this.Equals(other, SymbolEqualityComparer.Default.CompareKind);
}
bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind)
{
return this.Equals(other as Symbol, compareKind);
}
// By default we don't consider the compareKind, and do reference equality. This can be overridden.
public virtual bool Equals(Symbol other, TypeCompareKind compareKind)
{
return (object)this == other;
}
// By default, we do reference equality. This can be overridden.
public override int GetHashCode()
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this);
}
public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind)
{
if (first is null)
{
return second is null;
}
return first.Equals(second, compareKind);
}
/// <summary>
/// Returns a string representation of this symbol, suitable for debugging purposes, or
/// for placing in an error message.
/// </summary>
/// <remarks>
/// This will provide a useful representation, but it would be clearer to call <see cref="ToDisplayString"/>
/// directly and provide an explicit format.
/// Sealed so that <see cref="ToString"/> and <see cref="ToDisplayString"/> can't get out of sync.
/// </remarks>
public sealed override string ToString()
{
return this.ToDisplayString();
}
// ---- End of Public Definition ---
// Below here can be various useful virtual methods that are useful to the compiler, but we don't
// want to expose publicly.
// ---- End of Public Definition ---
// Must override this in derived classes for visitor pattern.
internal abstract TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a);
// Prevent anyone else from deriving from this class.
internal Symbol()
{
}
/// <summary>
/// Build and add synthesized attributes for this symbol.
/// </summary>
internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
}
/// <summary>
/// Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes.
/// </summary>
internal static void AddSynthesizedAttribute(ref ArrayBuilder<SynthesizedAttributeData> attributes, SynthesizedAttributeData attribute)
{
if (attribute != null)
{
if (attributes == null)
{
attributes = new ArrayBuilder<SynthesizedAttributeData>(1);
}
attributes.Add(attribute);
}
}
/// <summary>
/// <see cref="CharSet"/> effective for this symbol (type or DllImport method).
/// Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol.
/// </summary>
/// <remarks>
/// Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module.
/// </remarks>
internal CharSet? GetEffectiveDefaultMarshallingCharSet()
{
Debug.Assert(this.Kind == SymbolKind.NamedType || this.Kind == SymbolKind.Method);
return this.ContainingModule.DefaultMarshallingCharSet;
}
internal bool IsFromCompilation(CSharpCompilation compilation)
{
Debug.Assert(compilation != null);
return compilation == this.DeclaringCompilation;
}
/// <summary>
/// Always prefer <see cref="IsFromCompilation"/>.
/// </summary>
/// <remarks>
/// <para>
/// Unfortunately, when determining overriding/hiding/implementation relationships, we don't
/// have the "current" compilation available. We could, but that would clutter up the API
/// without providing much benefit. As a compromise, we consider all compilations "current".
/// </para>
/// <para>
/// Unlike in VB, we are not allowing retargeting symbols. This method is used as an approximation
/// for <see cref="IsFromCompilation"/> when a compilation is not available and that method will never return
/// true for retargeting symbols.
/// </para>
/// </remarks>
internal bool Dangerous_IsFromSomeCompilation
{
get { return this.DeclaringCompilation != null; }
}
internal virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken))
{
var declaringReferences = this.DeclaringSyntaxReferences;
if (this.IsImplicitlyDeclared && declaringReferences.Length == 0)
{
return this.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken);
}
foreach (var syntaxRef in declaringReferences)
{
cancellationToken.ThrowIfCancellationRequested();
if (syntaxRef.SyntaxTree == tree &&
(!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)))
{
return true;
}
}
return false;
}
internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken)
{
if (locationOpt == null || member.IsDefinedInSourceTree(locationOpt.SourceTree, locationOpt.SourceSpan, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
member.ForceComplete(locationOpt, cancellationToken);
}
}
/// <summary>
/// Returns the Documentation Comment ID for the symbol, or null if the symbol doesn't
/// support documentation comments.
/// </summary>
public virtual string GetDocumentationCommentId()
{
// NOTE: we're using a try-finally here because there's a test that specifically
// triggers an exception here to confirm that some symbols don't have documentation
// comment IDs. We don't care about "leaks" in such cases, but we don't want spew
// in the test output.
var pool = PooledStringBuilder.GetInstance();
try
{
StringBuilder builder = pool.Builder;
DocumentationCommentIDVisitor.Instance.Visit(this, builder);
return builder.Length == 0 ? null : builder.ToString();
}
finally
{
pool.Free();
}
}
#nullable enable
/// <summary>
/// Fetches the documentation comment for this element with a cancellation token.
/// </summary>
/// <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param>
/// <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param>
/// <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param>
/// <returns>The XML that would be written to the documentation file for the symbol.</returns>
public virtual string GetDocumentationCommentXml(
CultureInfo? preferredCulture = null,
bool expandIncludes = false,
CancellationToken cancellationToken = default(CancellationToken))
{
return "";
}
#nullable disable
private static readonly SymbolDisplayFormat s_debuggerDisplayFormat =
SymbolDisplayFormat.TestFormat
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier
| SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)
.WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
internal virtual string GetDebuggerDisplay()
{
return $"{this.Kind} {this.ToDisplayString(s_debuggerDisplayFormat)}";
}
internal virtual void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics)
{
#if DEBUG
if (ContainingSymbol is SourceMemberContainerTypeSymbol container)
{
container.AssertMemberExposure(this, forDiagnostics: true);
}
#endif
if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false || diagnostics.DependenciesBag?.Count > 0)
{
CSharpCompilation compilation = this.DeclaringCompilation;
Debug.Assert(compilation != null);
compilation.AddUsedAssemblies(diagnostics.DependenciesBag);
if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false)
{
compilation.DeclarationDiagnostics.AddRange(diagnostics.DiagnosticBag);
}
}
}
#region Use-Site Diagnostics
/// <summary>
/// True if the symbol has a use-site diagnostic with error severity.
/// </summary>
internal bool HasUseSiteError
{
get
{
var info = GetUseSiteInfo();
return info.DiagnosticInfo?.Severity == DiagnosticSeverity.Error;
}
}
/// <summary>
/// Returns diagnostic info that should be reported at the use site of the symbol, or default if there is none.
/// </summary>
internal virtual UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
return default;
}
protected AssemblySymbol PrimaryDependency
{
get
{
AssemblySymbol dependency = this.ContainingAssembly;
if (dependency is object && dependency.CorLibrary == dependency)
{
return null;
}
return dependency;
}
}
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// Supposed to be ErrorCode, but it causes inconsistent accessibility error.
/// </summary>
protected virtual int HighestPriorityUseSiteError
{
get
{
return int.MaxValue;
}
}
/// <summary>
/// Indicates that this symbol uses metadata that cannot be supported by the language.
///
/// Examples include:
/// - Pointer types in VB
/// - ByRef return type
/// - Required custom modifiers
///
/// This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced.
/// Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature.
///
/// This is set for metadata symbols, as follows:
/// Type - if a type is unsupported (e.g., a pointer type, etc.)
/// Method - parameter or return type is unsupported
/// Field - type is unsupported
/// Event - type is unsupported
/// Property - type is unsupported
/// Parameter - type is unsupported
/// </summary>
public virtual bool HasUnsupportedMetadata
{
get
{
return false;
}
}
/// <summary>
/// Merges given diagnostic to the existing result diagnostic.
/// </summary>
internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info)
{
if (info == null)
{
return false;
}
if (info.Severity == DiagnosticSeverity.Error && (info.Code == HighestPriorityUseSiteError || HighestPriorityUseSiteError == Int32.MaxValue))
{
// this error is final, no other error can override it:
result = info;
return true;
}
if (result == null || result.Severity == DiagnosticSeverity.Warning && info.Severity == DiagnosticSeverity.Error)
{
// there could be an error of higher-priority
result = info;
return false;
}
// we have a second low-pri error, continue looking for a higher priority one
return false;
}
/// <summary>
/// Merges given diagnostic and dependencies to the existing result.
/// </summary>
internal bool MergeUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result, UseSiteInfo<AssemblySymbol> info)
{
DiagnosticInfo diagnosticInfo = result.DiagnosticInfo;
bool retVal = MergeUseSiteDiagnostics(ref diagnosticInfo, info.DiagnosticInfo);
if (diagnosticInfo?.Severity == DiagnosticSeverity.Error)
{
result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo);
return retVal;
}
var secondaryDependencies = result.SecondaryDependencies;
var primaryDependency = result.PrimaryDependency;
info.MergeDependencies(ref primaryDependency, ref secondaryDependencies);
result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo, primaryDependency, secondaryDependencies);
Debug.Assert(!retVal);
return retVal;
}
/// <summary>
/// Reports specified use-site diagnostic to given diagnostic bag.
/// </summary>
/// <remarks>
/// This method should be the only method adding use-site diagnostics to a diagnostic bag.
/// It performs additional adjustments of the location for unification related diagnostics and
/// may be the place where to add more use-site location post-processing.
/// </remarks>
/// <returns>True if the diagnostic has error severity.</returns>
internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location)
{
// Unlike VB the C# Dev11 compiler reports only a single unification error/warning.
// By dropping the location we effectively merge all unification use-site errors that have the same error code into a single error.
// The error message clearly explains how to fix the problem and reporting the error for each location wouldn't add much value.
if (info.Code == (int)ErrorCode.WRN_UnifyReferenceBldRev ||
info.Code == (int)ErrorCode.WRN_UnifyReferenceMajMin ||
info.Code == (int)ErrorCode.ERR_AssemblyMatchBadVersion)
{
location = NoLocation.Singleton;
}
diagnostics.Add(info, location);
return info.Severity == DiagnosticSeverity.Error;
}
internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, BindingDiagnosticBag diagnostics, Location location)
{
return diagnostics.ReportUseSiteDiagnostic(info, location);
}
/// <summary>
/// Derive use-site info from a type symbol.
/// </summary>
internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeSymbol type)
{
UseSiteInfo<AssemblySymbol> info = type.GetUseSiteInfo();
if (info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType)
{
GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info);
}
return MergeUseSiteInfo(ref result, info);
}
private void GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref UseSiteInfo<AssemblySymbol> info)
{
switch (this.Kind)
{
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
info = info.AdjustDiagnosticInfo(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this));
break;
}
}
private UseSiteInfo<AssemblySymbol> GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo()
{
var useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty));
GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref useSiteInfo);
return useSiteInfo;
}
internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType)
{
return DeriveUseSiteInfoFromType(ref result, type.Type) ||
DeriveUseSiteInfoFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType);
}
internal bool DeriveUseSiteInfoFromParameter(ref UseSiteInfo<AssemblySymbol> result, ParameterSymbol param)
{
return DeriveUseSiteInfoFromType(ref result, param.TypeWithAnnotations, AllowedRequiredModifierType.None) ||
DeriveUseSiteInfoFromCustomModifiers(ref result, param.RefCustomModifiers,
this is MethodSymbol method && method.MethodKind == MethodKind.FunctionPointerSignature ?
AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute | AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute :
AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute);
}
internal bool DeriveUseSiteInfoFromParameters(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<ParameterSymbol> parameters)
{
foreach (ParameterSymbol param in parameters)
{
if (DeriveUseSiteInfoFromParameter(ref result, param))
{
return true;
}
}
return false;
}
[Flags]
internal enum AllowedRequiredModifierType
{
None = 0,
System_Runtime_CompilerServices_Volatile = 1,
System_Runtime_InteropServices_InAttribute = 1 << 1,
System_Runtime_CompilerServices_IsExternalInit = 1 << 2,
System_Runtime_CompilerServices_OutAttribute = 1 << 3,
}
internal bool DeriveUseSiteInfoFromCustomModifiers(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<CustomModifier> customModifiers, AllowedRequiredModifierType allowedRequiredModifierType)
{
AllowedRequiredModifierType requiredModifiersFound = AllowedRequiredModifierType.None;
bool checkRequiredModifiers = true;
foreach (CustomModifier modifier in customModifiers)
{
NamedTypeSymbol modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol;
if (checkRequiredModifiers && !modifier.IsOptional)
{
AllowedRequiredModifierType current = AllowedRequiredModifierType.None;
if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) != 0 &&
modifierType.IsWellKnownTypeInAttribute())
{
current = AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute;
}
else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile) != 0 &&
modifierType.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile)
{
current = AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile;
}
else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit) != 0 &&
modifierType.IsWellKnownTypeIsExternalInit())
{
current = AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit;
}
else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) != 0 &&
modifierType.IsWellKnownTypeOutAttribute())
{
current = AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute;
}
if (current == AllowedRequiredModifierType.None ||
(current != requiredModifiersFound && requiredModifiersFound != AllowedRequiredModifierType.None)) // At the moment we don't support applying different allowed modreqs to the same target.
{
if (MergeUseSiteInfo(ref result, GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo()))
{
return true;
}
checkRequiredModifiers = false;
}
requiredModifiersFound |= current;
}
// Unbound generic type is valid as a modifier, let's not report any use site diagnostics because of that.
if (modifierType.IsUnboundGenericType)
{
modifierType = modifierType.OriginalDefinition;
}
if (DeriveUseSiteInfoFromType(ref result, modifierType))
{
return true;
}
}
return false;
}
internal static bool GetUnificationUseSiteDiagnosticRecursive<T>(ref DiagnosticInfo result, ImmutableArray<T> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) where T : TypeSymbol
{
foreach (var t in types)
{
if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes))
{
return true;
}
}
return false;
}
internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeWithAnnotations> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
foreach (var t in types)
{
if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes))
{
return true;
}
}
return false;
}
internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<CustomModifier> modifiers, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
foreach (var modifier in modifiers)
{
if (((CSharpCustomModifier)modifier).ModifierSymbol.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes))
{
return true;
}
}
return false;
}
internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<ParameterSymbol> parameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
foreach (var parameter in parameters)
{
if (parameter.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) ||
GetUnificationUseSiteDiagnosticRecursive(ref result, parameter.RefCustomModifiers, owner, ref checkedTypes))
{
return true;
}
}
return false;
}
internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeParameterSymbol> typeParameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
foreach (var typeParameter in typeParameters)
{
if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeParameter.ConstraintTypesNoUseSiteDiagnostics, owner, ref checkedTypes))
{
return true;
}
}
return false;
}
#endregion
/// <summary>
/// True if this symbol has been marked with the <see cref="ObsoleteAttribute"/> attribute.
/// This property returns <see cref="ThreeState.Unknown"/> if the <see cref="ObsoleteAttribute"/> attribute hasn't been cracked yet.
/// </summary>
internal ThreeState ObsoleteState
{
get
{
switch (ObsoleteKind)
{
case ObsoleteAttributeKind.None:
case ObsoleteAttributeKind.Experimental:
return ThreeState.False;
case ObsoleteAttributeKind.Uninitialized:
return ThreeState.Unknown;
default:
return ThreeState.True;
}
}
}
internal ObsoleteAttributeKind ObsoleteKind
{
get
{
var data = this.ObsoleteAttributeData;
return (data == null) ? ObsoleteAttributeKind.None : data.Kind;
}
}
/// <summary>
/// Returns data decoded from <see cref="ObsoleteAttribute"/> attribute or null if there is no <see cref="ObsoleteAttribute"/> attribute.
/// This property returns <see cref="Microsoft.CodeAnalysis.ObsoleteAttributeData.Uninitialized"/> if attribute arguments haven't been decoded yet.
/// </summary>
internal abstract ObsoleteAttributeData ObsoleteAttributeData { get; }
/// <summary>
/// Returns true and a <see cref="string"/> from the first <see cref="GuidAttribute"/> on the symbol,
/// the string might be null or an invalid guid representation. False,
/// if there is no <see cref="GuidAttribute"/> with string argument.
/// </summary>
internal bool GetGuidStringDefaultImplementation(out string guidString)
{
foreach (var attrData in this.GetAttributes())
{
if (attrData.IsTargetAttribute(this, AttributeDescription.GuidAttribute))
{
if (attrData.TryGetGuidAttributeValue(out guidString))
{
return true;
}
}
}
guidString = null;
return false;
}
public string ToDisplayString(SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayString(ISymbol, format);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayParts(ISymbol, format);
}
public string ToMinimalDisplayString(
SemanticModel semanticModel,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayString(ISymbol, semanticModel, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayParts(ISymbol, semanticModel, position, format);
}
internal static void ReportErrorIfHasConstraints(
SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, DiagnosticBag diagnostics)
{
if (constraintClauses.Count > 0)
{
diagnostics.Add(
ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl,
constraintClauses[0].WhereKeyword.GetLocation());
}
}
internal static void CheckForBlockAndExpressionBody(
CSharpSyntaxNode block,
CSharpSyntaxNode expression,
CSharpSyntaxNode syntax,
BindingDiagnosticBag diagnostics)
{
if (block != null && expression != null)
{
diagnostics.Add(ErrorCode.ERR_BlockBodyAndExpressionBody, syntax.GetLocation());
}
}
[Flags]
internal enum ReservedAttributes
{
DynamicAttribute = 1 << 1,
IsReadOnlyAttribute = 1 << 2,
IsUnmanagedAttribute = 1 << 3,
IsByRefLikeAttribute = 1 << 4,
TupleElementNamesAttribute = 1 << 5,
NullableAttribute = 1 << 6,
NullableContextAttribute = 1 << 7,
NullablePublicOnlyAttribute = 1 << 8,
NativeIntegerAttribute = 1 << 9,
CaseSensitiveExtensionAttribute = 1 << 10,
}
internal bool ReportExplicitUseOfReservedAttributes(in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, ReservedAttributes reserved)
{
var attribute = arguments.Attribute;
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
if ((reserved & ReservedAttributes.DynamicAttribute) != 0 &&
attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute))
{
// DynamicAttribute should not be set explicitly.
diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location);
}
else if ((reserved & ReservedAttributes.IsReadOnlyAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsReadOnlyAttribute))
{
}
else if ((reserved & ReservedAttributes.IsUnmanagedAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsUnmanagedAttribute))
{
}
else if ((reserved & ReservedAttributes.IsByRefLikeAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsByRefLikeAttribute))
{
}
else if ((reserved & ReservedAttributes.TupleElementNamesAttribute) != 0 &&
attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute))
{
diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location);
}
else if ((reserved & ReservedAttributes.NullableAttribute) != 0 &&
attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute))
{
// NullableAttribute should not be set explicitly.
diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location);
}
else if ((reserved & ReservedAttributes.NullableContextAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullableContextAttribute))
{
}
else if ((reserved & ReservedAttributes.NullablePublicOnlyAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullablePublicOnlyAttribute))
{
}
else if ((reserved & ReservedAttributes.NativeIntegerAttribute) != 0 &&
reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NativeIntegerAttribute))
{
}
else if ((reserved & ReservedAttributes.CaseSensitiveExtensionAttribute) != 0 &&
attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute))
{
// ExtensionAttribute should not be set explicitly.
diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location);
}
else
{
return false;
}
return true;
bool reportExplicitUseOfReservedAttribute(CSharpAttributeData attribute, in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, in AttributeDescription attributeDescription)
{
if (attribute.IsTargetAttribute(this, attributeDescription))
{
// Do not use '{FullName}'. This is reserved for compiler usage.
diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, attributeDescription.FullName);
return true;
}
return false;
}
}
internal virtual byte? GetNullableContextValue()
{
return GetLocalNullableContextValue() ?? ContainingSymbol?.GetNullableContextValue();
}
internal virtual byte? GetLocalNullableContextValue()
{
return null;
}
internal void GetCommonNullableValues(CSharpCompilation compilation, ref MostCommonNullableValueBuilder builder)
{
switch (this.Kind)
{
case SymbolKind.NamedType:
if (compilation.ShouldEmitNullableAttributes(this))
{
builder.AddValue(this.GetLocalNullableContextValue());
}
break;
case SymbolKind.Event:
if (compilation.ShouldEmitNullableAttributes(this))
{
builder.AddValue(((EventSymbol)this).TypeWithAnnotations);
}
break;
case SymbolKind.Field:
var field = (FieldSymbol)this;
if (field is TupleElementFieldSymbol tupleElement)
{
field = tupleElement.TupleUnderlyingField;
}
if (compilation.ShouldEmitNullableAttributes(field))
{
builder.AddValue(field.TypeWithAnnotations);
}
break;
case SymbolKind.Method:
if (compilation.ShouldEmitNullableAttributes(this))
{
builder.AddValue(this.GetLocalNullableContextValue());
}
break;
case SymbolKind.Property:
if (compilation.ShouldEmitNullableAttributes(this))
{
builder.AddValue(((PropertySymbol)this).TypeWithAnnotations);
// Attributes are not emitted for property parameters.
}
break;
case SymbolKind.Parameter:
builder.AddValue(((ParameterSymbol)this).TypeWithAnnotations);
break;
case SymbolKind.TypeParameter:
if (this is SourceTypeParameterSymbolBase typeParameter)
{
builder.AddValue(typeParameter.GetSynthesizedNullableAttributeValue());
foreach (var constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics)
{
builder.AddValue(constraintType);
}
}
break;
}
}
internal bool ShouldEmitNullableContextValue(out byte value)
{
byte? localValue = GetLocalNullableContextValue();
if (localValue == null)
{
value = 0;
return false;
}
value = localValue.GetValueOrDefault();
byte containingValue = ContainingSymbol?.GetNullableContextValue() ?? 0;
return value != containingValue;
}
#nullable enable
/// <summary>
/// True if the symbol is declared outside of the scope of the containing
/// symbol
/// </summary>
internal static bool IsCaptured(Symbol variable, SourceMethodSymbol containingSymbol)
{
switch (variable.Kind)
{
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
// Range variables are not captured, but their underlying parameters
// may be. If this is a range underlying parameter it will be a
// ParameterSymbol, not a RangeVariableSymbol.
case SymbolKind.RangeVariable:
return false;
case SymbolKind.Local:
if (((LocalSymbol)variable).IsConst)
{
return false;
}
break;
case SymbolKind.Parameter:
break;
case SymbolKind.Method:
if (variable is LocalFunctionSymbol localFunction)
{
// calling a static local function doesn't require capturing state
if (localFunction.IsStatic)
{
return false;
}
break;
}
throw ExceptionUtilities.UnexpectedValue(variable);
default:
throw ExceptionUtilities.UnexpectedValue(variable.Kind);
}
// Walk up the containing symbols until we find the target function, in which
// case the variable is not captured by the target function, or null, in which
// case it is.
for (var currentFunction = variable.ContainingSymbol;
(object)currentFunction != null;
currentFunction = currentFunction.ContainingSymbol)
{
if (ReferenceEquals(currentFunction, containingSymbol))
{
return false;
}
}
return true;
}
#nullable disable
bool ISymbolInternal.IsStatic
{
get { return this.IsStatic; }
}
bool ISymbolInternal.IsVirtual
{
get { return this.IsVirtual; }
}
bool ISymbolInternal.IsOverride
{
get { return this.IsOverride; }
}
bool ISymbolInternal.IsAbstract
{
get
{
return this.IsAbstract;
}
}
Accessibility ISymbolInternal.DeclaredAccessibility
{
get
{
return this.DeclaredAccessibility;
}
}
public abstract void Accept(CSharpSymbolVisitor visitor);
public abstract TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor);
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return ToString();
}
protected abstract ISymbol CreateISymbol();
internal ISymbol ISymbol
{
get
{
if (_lazyISymbol is null)
{
Interlocked.CompareExchange(ref _lazyISymbol, CreateISymbol(), null);
}
return _lazyISymbol;
}
}
}
}
| mit |
diegoeis/locawebstyle | source/assets/javascripts/templates.js | 99 | //= require locastyle/templates/_popover.jst.eco
//= require locastyle/templates/_dropdown.jst.eco
| mit |
rkq/cxxexp | third-party/src/boost_1_56_0/doc/html/boost_asio/reference/basic_socket_acceptor/bind/overload2.html | 7421 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket_acceptor::bind (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../bind.html" title="basic_socket_acceptor::bind">
<link rel="prev" href="overload1.html" title="basic_socket_acceptor::bind (1 of 2 overloads)">
<link rel="next" href="../broadcast.html" title="basic_socket_acceptor::broadcast">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../bind.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../broadcast.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_socket_acceptor.bind.overload2"></a><a class="link" href="overload2.html" title="basic_socket_acceptor::bind (2 of 2 overloads)">basic_socket_acceptor::bind
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Bind the acceptor to the given local endpoint.
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">bind</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">endpoint_type</span> <span class="special">&</span> <span class="identifier">endpoint</span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<p>
This function binds the socket acceptor to the specified endpoint on
the local machine.
</p>
<h6>
<a name="boost_asio.reference.basic_socket_acceptor.bind.overload2.h0"></a>
<span class="phrase"><a name="boost_asio.reference.basic_socket_acceptor.bind.overload2.parameters"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_socket_acceptor.bind.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl class="variablelist">
<dt><span class="term">endpoint</span></dt>
<dd><p>
An endpoint on the local machine to which the socket acceptor will
be bound.
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_socket_acceptor.bind.overload2.h1"></a>
<span class="phrase"><a name="boost_asio.reference.basic_socket_acceptor.bind.overload2.example"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_socket_acceptor.bind.overload2.example">Example</a>
</h6>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">acceptor</span> <span class="identifier">acceptor</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">);</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">endpoint</span> <span class="identifier">endpoint</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">v4</span><span class="special">(),</span> <span class="number">12345</span><span class="special">);</span>
<span class="identifier">acceptor</span><span class="special">.</span><span class="identifier">open</span><span class="special">(</span><span class="identifier">endpoint</span><span class="special">.</span><span class="identifier">protocol</span><span class="special">());</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">ec</span><span class="special">;</span>
<span class="identifier">acceptor</span><span class="special">.</span><span class="identifier">bind</span><span class="special">(</span><span class="identifier">endpoint</span><span class="special">,</span> <span class="identifier">ec</span><span class="special">);</span>
<span class="keyword">if</span> <span class="special">(</span><span class="identifier">ec</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// An error occurred.</span>
<span class="special">}</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2014 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../bind.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../broadcast.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
AzureZhao/android-developer-cn | sdk/api_diff/8/changes/classes_index_changes.html | 36742 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Class Changes Index
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY class="gc-documentation" style="padding:12px;">
<a NAME="topheader"></a>
<table summary="Index for Classes" width="100%" class="jdiffIndex" border="0" cellspacing="0" cellpadding="0" style="padding-bottom:0;margin-bottom:0;">
<tr>
<th class="indexHeader">
Filter the Index:
</th>
</tr>
<tr>
<td class="indexText" style="line-height:1.3em;padding-left:2em;">
<a href="classes_index_all.html" class="staysblack">All Classes</a>
<br>
<font color="#999999">Removals</font>
<br>
<A HREF="classes_index_additions.html"xclass="hiddenlink">Additions</A>
<br>
<b>Changes</b>
</td>
</tr>
</table>
<div id="indexTableCaption" style="background-color:#eee;padding:0 4px 0 4px;font-size:11px;margin-bottom:1em;">
Listed as: <span style="color:#069"><strong>Added</strong></span>, <span style="color:#069"><strike>Removed</strike></span>, <span style="color:#069">Changed</span></font>
</div>
<A NAME="A"></A>
<br><font size="+2">A</font>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.widget.AbsListView.html" class="hiddenlink" target="rightframe">AbsListView</A><br>
<A HREF="android.content.AbstractThreadedSyncAdapter.html" class="hiddenlink" target="rightframe">AbstractThreadedSyncAdapter</A><br>
<A HREF="android.accounts.AccountManager.html" class="hiddenlink" target="rightframe">AccountManager</A><br>
<A HREF="android.app.Activity.html" class="hiddenlink" target="rightframe">Activity</A><br>
<A HREF="android.content.pm.ActivityInfo.html" class="hiddenlink" target="rightframe">ActivityInfo</A><br>
<A HREF="android.test.ActivityInstrumentationTestCase2.html" class="hiddenlink" target="rightframe">ActivityInstrumentationTestCase2</A><br>
<A HREF="android.app.ActivityManager.html" class="hiddenlink" target="rightframe">ActivityManager</A><br>
<A HREF="android.app.ActivityManager.ProcessErrorStateInfo.html" class="hiddenlink" target="rightframe">ActivityManager.ProcessErrorStateInfo</A><br>
<A HREF="android.app.AlarmManager.html" class="hiddenlink" target="rightframe">AlarmManager</A><br>
<A HREF="android.text.AndroidCharacter.html" class="hiddenlink" target="rightframe">AndroidCharacter</A><br>
<A HREF="android.view.animation.Animation.html" class="hiddenlink" target="rightframe">Animation</A><br>
<A HREF="android.content.pm.ApplicationInfo.html" class="hiddenlink" target="rightframe">ApplicationInfo</A><br>
<A HREF="java.util.ArrayList.html" class="hiddenlink" target="rightframe">ArrayList</A><br>
<A HREF="org.w3c.dom.Attr.html" class="hiddenlink" target="rightframe"><i>Attr</i></A><br>
<A HREF="android.media.AudioManager.html" class="hiddenlink" target="rightframe">AudioManager</A><br>
<A NAME="B"></A>
<br><font size="+2">B</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.widget.BaseExpandableListAdapter.html" class="hiddenlink" target="rightframe">BaseExpandableListAdapter</A><br>
<A HREF="android.provider.Browser.html" class="hiddenlink" target="rightframe">Browser</A><br>
<A HREF="android.os.Build.html" class="hiddenlink" target="rightframe">Build</A><br>
<A HREF="android.os.Build.VERSION_CODES.html" class="hiddenlink" target="rightframe">Build.VERSION_CODES</A><br>
<A HREF="android.os.Bundle.html" class="hiddenlink" target="rightframe">Bundle</A><br>
<A NAME="C"></A>
<br><font size="+2">C</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.webkit.CacheManager.html" class="hiddenlink" target="rightframe">CacheManager</A><br>
<A HREF="android.provider.CallLog.Calls.html" class="hiddenlink" target="rightframe">CallLog.Calls</A><br>
<A HREF="android.hardware.Camera.html" class="hiddenlink" target="rightframe">Camera</A><br>
<A HREF="android.hardware.Camera.Parameters.html" class="hiddenlink" target="rightframe">Camera.Parameters</A><br>
<A HREF="java.nio.charset.Charset.html" class="hiddenlink" target="rightframe">Charset</A><br>
<A HREF="android.content.pm.ComponentInfo.html" class="hiddenlink" target="rightframe">ComponentInfo</A><br>
<A HREF="android.content.ComponentName.html" class="hiddenlink" target="rightframe">ComponentName</A><br>
<A HREF="android.content.res.Configuration.html" class="hiddenlink" target="rightframe">Configuration</A><br>
<A HREF="android.net.ConnectivityManager.html" class="hiddenlink" target="rightframe">ConnectivityManager</A><br>
<A HREF="android.provider.Contacts.PresenceColumns.html" class="hiddenlink" target="rightframe"><i>Contacts.PresenceColumns</i></A><br>
<A HREF="android.provider.ContactsContract.Groups.html" class="hiddenlink" target="rightframe">ContactsContract.Groups</A><br>
<A HREF="android.provider.ContactsContract.RawContacts.html" class="hiddenlink" target="rightframe">ContactsContract.RawContacts</A><br>
<A HREF="android.provider.ContactsContract.StatusColumns.html" class="hiddenlink" target="rightframe"><i>ContactsContract.StatusColumns</i></A><br>
<A HREF="android.content.ContentResolver.html" class="hiddenlink" target="rightframe">ContentResolver</A><br>
<A HREF="android.content.Context.html" class="hiddenlink" target="rightframe">Context</A><br>
<A HREF="android.content.ContextWrapper.html" class="hiddenlink" target="rightframe">ContextWrapper</A><br>
<A NAME="D"></A>
<br><font size="+2">D</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.database.DatabaseUtils.html" class="hiddenlink" target="rightframe">DatabaseUtils</A><br>
<A HREF="java.net.DatagramSocketImpl.html" class="hiddenlink" target="rightframe">DatagramSocketImpl</A><br>
<A HREF="android.os.Debug.html" class="hiddenlink" target="rightframe">Debug</A><br>
<A HREF="android.app.Dialog.html" class="hiddenlink" target="rightframe">Dialog</A><br>
<A HREF="android.view.Display.html" class="hiddenlink" target="rightframe">Display</A><br>
<A HREF="org.w3c.dom.Document.html" class="hiddenlink" target="rightframe"><i>Document</i></A><br>
<A HREF="javax.xml.parsers.DocumentBuilder.html" class="hiddenlink" target="rightframe">DocumentBuilder</A><br>
<A HREF="javax.xml.parsers.DocumentBuilderFactory.html" class="hiddenlink" target="rightframe">DocumentBuilderFactory</A><br>
<A HREF="org.w3c.dom.DOMException.html" class="hiddenlink" target="rightframe">DOMException</A><br>
<A HREF="org.w3c.dom.DOMImplementation.html" class="hiddenlink" target="rightframe"><i>DOMImplementation</i></A><br>
<A NAME="E"></A>
<br><font size="+2">E</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="org.w3c.dom.Element.html" class="hiddenlink" target="rightframe"><i>Element</i></A><br>
<A HREF="org.w3c.dom.Entity.html" class="hiddenlink" target="rightframe"><i>Entity</i></A><br>
<A HREF="android.os.Environment.html" class="hiddenlink" target="rightframe">Environment</A><br>
<A HREF="android.util.EventLogTags.html" class="hiddenlink" target="rightframe">EventLogTags</A><br>
<A HREF="android.media.ExifInterface.html" class="hiddenlink" target="rightframe">ExifInterface</A><br>
<A NAME="G"></A>
<br><font size="+2">G</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.gesture.Gesture.html" class="hiddenlink" target="rightframe">Gesture</A><br>
<A HREF="android.view.GestureDetector.html" class="hiddenlink" target="rightframe">GestureDetector</A><br>
<A HREF="android.gesture.GesturePoint.html" class="hiddenlink" target="rightframe">GesturePoint</A><br>
<A HREF="android.gesture.GestureStroke.html" class="hiddenlink" target="rightframe">GestureStroke</A><br>
<A HREF="android.opengl.GLSurfaceView.html" class="hiddenlink" target="rightframe">GLSurfaceView</A><br>
<A NAME="H"></A>
<br><font size="+2">H</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.view.HapticFeedbackConstants.html" class="hiddenlink" target="rightframe">HapticFeedbackConstants</A><br>
<A HREF="java.util.HashMap.html" class="hiddenlink" target="rightframe">HashMap</A><br>
<A NAME="I"></A>
<br><font size="+2">I</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.widget.ImageView.html" class="hiddenlink" target="rightframe">ImageView</A><br>
<A HREF="android.content.Intent.html" class="hiddenlink" target="rightframe">Intent</A><br>
<A NAME="J"></A>
<br><font size="+2">J</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.webkit.JsResult.html" class="hiddenlink" target="rightframe">JsResult</A><br>
<A NAME="L"></A>
<br><font size="+2">L</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.widget.ListView.html" class="hiddenlink" target="rightframe">ListView</A><br>
<A HREF="android.location.LocationManager.html" class="hiddenlink" target="rightframe">LocationManager</A><br>
<A HREF="android.util.Log.html" class="hiddenlink" target="rightframe">Log</A><br>
<A NAME="M"></A>
<br><font size="+2">M</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.Manifest.permission.html" class="hiddenlink" target="rightframe">Manifest.permission</A><br>
<A HREF="java.util.regex.Matcher.html" class="hiddenlink" target="rightframe">Matcher</A><br>
<A HREF="android.opengl.Matrix.html" class="hiddenlink" target="rightframe">Matrix</A><br>
<A HREF="android.media.MediaRecorder.html" class="hiddenlink" target="rightframe">MediaRecorder</A><br>
<A HREF="android.media.MediaScannerConnection.html" class="hiddenlink" target="rightframe">MediaScannerConnection</A><br>
<A HREF="android.media.MediaScannerConnection.MediaScannerConnectionClient.html" class="hiddenlink" target="rightframe"><i>MediaScannerConnection.MediaScannerConnectionClient</i></A><br>
<A HREF="android.provider.MediaStore.html" class="hiddenlink" target="rightframe">MediaStore</A><br>
<A HREF="android.provider.MediaStore.Audio.AudioColumns.html" class="hiddenlink" target="rightframe"><i>MediaStore.Audio.AudioColumns</i></A><br>
<A HREF="android.provider.MediaStore.Audio.Playlists.Members.html" class="hiddenlink" target="rightframe">MediaStore.Audio.Playlists.Members</A><br>
<A HREF="android.provider.MediaStore.Images.Thumbnails.html" class="hiddenlink" target="rightframe">MediaStore.Images.Thumbnails</A><br>
<A HREF="android.provider.MediaStore.Video.Thumbnails.html" class="hiddenlink" target="rightframe">MediaStore.Video.Thumbnails</A><br>
<A HREF="android.test.mock.MockContext.html" class="hiddenlink" target="rightframe">MockContext</A><br>
<A HREF="android.test.mock.MockPackageManager.html" class="hiddenlink" target="rightframe">MockPackageManager</A><br>
<A HREF="android.view.MotionEvent.html" class="hiddenlink" target="rightframe">MotionEvent</A><br>
<A NAME="N"></A>
<br><font size="+2">N</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="org.w3c.dom.NamedNodeMap.html" class="hiddenlink" target="rightframe"><i>NamedNodeMap</i></A><br>
<A HREF="org.w3c.dom.Node.html" class="hiddenlink" target="rightframe"><i>Node</i></A><br>
<A NAME="O"></A>
<br><font size="+2">O</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="dalvik.bytecode.Opcodes.html" class="hiddenlink" target="rightframe"><i>Opcodes</i></A><br>
<A NAME="P"></A>
<br><font size="+2">P</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.content.pm.PackageManager.html" class="hiddenlink" target="rightframe">PackageManager</A><br>
<A HREF="java.util.regex.Pattern.html" class="hiddenlink" target="rightframe">Pattern</A><br>
<A HREF="android.graphics.PixelFormat.html" class="hiddenlink" target="rightframe">PixelFormat</A><br>
<A HREF="android.os.PowerManager.html" class="hiddenlink" target="rightframe">PowerManager</A><br>
<A NAME="R"></A>
<br><font size="+2">R</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.R.anim.html" class="hiddenlink" target="rightframe">R.anim</A><br>
<A HREF="android.R.attr.html" class="hiddenlink" target="rightframe">R.attr</A><br>
<A HREF="android.R.id.html" class="hiddenlink" target="rightframe">R.id</A><br>
<A HREF="android.speech.RecognizerIntent.html" class="hiddenlink" target="rightframe">RecognizerIntent</A><br>
<A HREF="android.widget.RemoteViews.html" class="hiddenlink" target="rightframe">RemoteViews</A><br>
<A HREF="android.text.util.Rfc822Tokenizer.html" class="hiddenlink" target="rightframe">Rfc822Tokenizer</A><br>
<A NAME="S"></A>
<br><font size="+2">S</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="javax.xml.parsers.SAXParser.html" class="hiddenlink" target="rightframe">SAXParser</A><br>
<A HREF="javax.xml.parsers.SAXParserFactory.html" class="hiddenlink" target="rightframe">SAXParserFactory</A><br>
<A HREF="android.app.SearchManager.html" class="hiddenlink" target="rightframe">SearchManager</A><br>
<A HREF="android.hardware.Sensor.html" class="hiddenlink" target="rightframe">Sensor</A><br>
<A HREF="android.provider.Settings.html" class="hiddenlink" target="rightframe">Settings</A><br>
<A HREF="android.provider.Settings.Secure.html" class="hiddenlink" target="rightframe">Settings.Secure</A><br>
<A HREF="android.provider.Settings.System.html" class="hiddenlink" target="rightframe">Settings.System</A><br>
<A HREF="android.media.SoundPool.html" class="hiddenlink" target="rightframe">SoundPool</A><br>
<A HREF="android.database.sqlite.SQLiteDatabase.html" class="hiddenlink" target="rightframe">SQLiteDatabase</A><br>
<A HREF="android.database.sqlite.SQLiteProgram.html" class="hiddenlink" target="rightframe">SQLiteProgram</A><br>
<A HREF="android.net.http.SslCertificate.html" class="hiddenlink" target="rightframe">SslCertificate</A><br>
<A HREF="android.net.SSLCertificateSocketFactory.html" class="hiddenlink" target="rightframe">SSLCertificateSocketFactory</A><br>
<A HREF="android.content.SyncResult.html" class="hiddenlink" target="rightframe">SyncResult</A><br>
<A NAME="T"></A>
<br><font size="+2">T</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.widget.TabWidget.html" class="hiddenlink" target="rightframe">TabWidget</A><br>
<A HREF="android.telephony.TelephonyManager.html" class="hiddenlink" target="rightframe">TelephonyManager</A><br>
<A HREF="org.w3c.dom.Text.html" class="hiddenlink" target="rightframe"><i>Text</i></A><br>
<A HREF="android.speech.tts.TextToSpeech.html" class="hiddenlink" target="rightframe">TextToSpeech</A><br>
<A HREF="android.speech.tts.TextToSpeech.Engine.html" class="hiddenlink" target="rightframe">TextToSpeech.Engine</A><br>
<A NAME="V"></A>
<br><font size="+2">V</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.view.VelocityTracker.html" class="hiddenlink" target="rightframe">VelocityTracker</A><br>
<A HREF="android.widget.VideoView.html" class="hiddenlink" target="rightframe">VideoView</A><br>
<A HREF="android.view.View.html" class="hiddenlink" target="rightframe">View</A><br>
<A HREF="android.view.ViewConfiguration.html" class="hiddenlink" target="rightframe">ViewConfiguration</A><br>
<A HREF="android.view.ViewGroup.LayoutParams.html" class="hiddenlink" target="rightframe">ViewGroup.LayoutParams</A><br>
<A HREF="dalvik.system.VMDebug.html" class="hiddenlink" target="rightframe">VMDebug</A><br>
<A NAME="W"></A>
<br><font size="+2">W</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="android.webkit.WebChromeClient.html" class="hiddenlink" target="rightframe">WebChromeClient</A><br>
<A HREF="android.webkit.WebSettings.html" class="hiddenlink" target="rightframe">WebSettings</A><br>
<A HREF="android.webkit.WebView.html" class="hiddenlink" target="rightframe">WebView</A><br>
<A HREF="android.webkit.WebViewClient.html" class="hiddenlink" target="rightframe">WebViewClient</A><br>
<A HREF="android.view.WindowManager.LayoutParams.html" class="hiddenlink" target="rightframe">WindowManager.LayoutParams</A><br>
<A NAME="X"></A>
<br><font size="+2">X</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#Z"><font size="-2">Z</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="javax.xml.XMLConstants.html" class="hiddenlink" target="rightframe">XMLConstants</A><br>
<A NAME="Z"></A>
<br><font size="+2">Z</font>
<a href="#A"><font size="-2">A</font></a>
<a href="#B"><font size="-2">B</font></a>
<a href="#C"><font size="-2">C</font></a>
<a href="#D"><font size="-2">D</font></a>
<a href="#E"><font size="-2">E</font></a>
<a href="#G"><font size="-2">G</font></a>
<a href="#H"><font size="-2">H</font></a>
<a href="#I"><font size="-2">I</font></a>
<a href="#J"><font size="-2">J</font></a>
<a href="#L"><font size="-2">L</font></a>
<a href="#M"><font size="-2">M</font></a>
<a href="#N"><font size="-2">N</font></a>
<a href="#O"><font size="-2">O</font></a>
<a href="#P"><font size="-2">P</font></a>
<a href="#R"><font size="-2">R</font></a>
<a href="#S"><font size="-2">S</font></a>
<a href="#T"><font size="-2">T</font></a>
<a href="#V"><font size="-2">V</font></a>
<a href="#W"><font size="-2">W</font></a>
<a href="#X"><font size="-2">X</font></a>
<a href="#topheader"><font size="-2">TOP</font></a>
<p><div style="line-height:1.5em;color:black">
<A HREF="dalvik.system.Zygote.html" class="hiddenlink" target="rightframe">Zygote</A><br>
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| mit |
jordanwalsh23/jordanwalsh23.github.io | core/server/api/mail.js | 3802 | // # Mail API
// API for sending Mail
var Promise = require('bluebird'),
pipeline = require('../utils/pipeline'),
errors = require('../errors'),
mail = require('../mail'),
Models = require('../models'),
utils = require('./utils'),
notifications = require('./notifications'),
i18n = require('../i18n'),
docName = 'mail',
mailer,
apiMail;
/**
* Send mail helper
*/
function sendMail(object) {
if (!(mailer instanceof mail.GhostMailer)) {
mailer = new mail.GhostMailer();
}
return mailer.send(object.mail[0].message).catch(function (err) {
if (mailer.state.usingDirect) {
notifications.add(
{notifications: [{
type: 'warn',
message: [
i18n.t('warnings.index.unableToSendEmail'),
i18n.t('common.seeLinkForInstructions',
{link: '<a href=\'https://docs.ghost.org/v1.0.0/docs/mail-config\' target=\'_blank\'>Checkout our mail configuration docs!</a>'})
].join(' ')
}]},
{context: {internal: true}}
);
}
return Promise.reject(new errors.EmailError({err: err}));
});
}
/**
* ## Mail API Methods
*
* **See:** [API Methods](index.js.html#api%20methods)
* @typedef Mail
* @param mail
*/
apiMail = {
/**
* ### Send
* Send an email
*
* @public
* @param {Mail} object details of the email to send
* @returns {Promise}
*/
send: function (object, options) {
var tasks;
/**
* ### Format Response
* @returns {Mail} mail
*/
function formatResponse(data) {
delete object.mail[0].options;
// Sendmail returns extra details we don't need and that don't convert to JSON
delete object.mail[0].message.transport;
object.mail[0].status = {
message: data.message
};
return object;
}
/**
* ### Send Mail
*/
function send() {
return sendMail(object, options);
}
tasks = [
utils.handlePermissions(docName, 'send'),
send,
formatResponse
];
return pipeline(tasks, options || {});
},
/**
* ### SendTest
* Send a test email
*
* @public
* @param {Object} options required property 'to' which contains the recipient address
* @returns {Promise}
*/
sendTest: function (options) {
var tasks;
/**
* ### Model Query
*/
function modelQuery() {
return Models.User.findOne({id: options.context.user});
}
/**
* ### Generate content
*/
function generateContent(result) {
return mail.utils.generateContent({template: 'test'}).then(function (content) {
var payload = {
mail: [{
message: {
to: result.get('email'),
subject: i18n.t('common.api.mail.testGhostEmail'),
html: content.html,
text: content.text
}
}]
};
return payload;
});
}
/**
* ### Send mail
*/
function send(payload) {
return sendMail(payload, options);
}
tasks = [
modelQuery,
generateContent,
send
];
return pipeline(tasks);
}
};
module.exports = apiMail;
| mit |
TeamTorch5942/ftc_app | docs-FTC/javadoc/com/qualcomm/robotcore/util/ElapsedTime.html | 16485 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Tue Feb 09 12:58:20 EST 2016 -->
<title>ElapsedTime</title>
<meta name="date" content="2016-02-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ElapsedTime";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/qualcomm/robotcore/util/DifferentialControlLoopCoefficients.html" title="class in com.qualcomm.robotcore.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/qualcomm/robotcore/util/ElapsedTime.html" target="_top">Frames</a></li>
<li><a href="ElapsedTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.qualcomm.robotcore.util</div>
<h2 title="Class ElapsedTime" class="title">Class ElapsedTime</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.qualcomm.robotcore.util.ElapsedTime</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">ElapsedTime</span>
extends java.lang.Object</pre>
<div class="block">Measure elapsed time
<p>
Does not measure deep sleep. Nanosecond accuracy.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util">ElapsedTime.Resolution</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#dMILLIS_IN_NANO">dMILLIS_IN_NANO</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#dSECOND_IN_NANO">dSECOND_IN_NANO</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static long</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#lMILLIS_IN_NANO">lMILLIS_IN_NANO</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static long</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#lSECOND_IN_NANO">lSECOND_IN_NANO</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#ElapsedTime()">ElapsedTime</a></strong>()</code>
<div class="block">Constructor</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#ElapsedTime(com.qualcomm.robotcore.util.ElapsedTime.Resolution)">ElapsedTime</a></strong>(<a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util">ElapsedTime.Resolution</a> resolution)</code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#ElapsedTime(long)">ElapsedTime</a></strong>(long startTime)</code>
<div class="block">Constructor</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#log(java.lang.String)">log</a></strong>(java.lang.String label)</code>
<div class="block">Log a message stating how long the timer has been running</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#reset()">reset</a></strong>()</code>
<div class="block">Reset the start time to now</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#startTime()">startTime</a></strong>()</code>
<div class="block">Get the relative start time</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#time()">time</a></strong>()</code>
<div class="block">How many seconds since the start time.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.html#toString()">toString</a></strong>()</code>
<div class="block">Return a string stating the number of seconds that have passed</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="dSECOND_IN_NANO">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>dSECOND_IN_NANO</h4>
<pre>public static final double dSECOND_IN_NANO</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.qualcomm.robotcore.util.ElapsedTime.dSECOND_IN_NANO">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="lSECOND_IN_NANO">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>lSECOND_IN_NANO</h4>
<pre>public static final long lSECOND_IN_NANO</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.qualcomm.robotcore.util.ElapsedTime.lSECOND_IN_NANO">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="dMILLIS_IN_NANO">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>dMILLIS_IN_NANO</h4>
<pre>public static final double dMILLIS_IN_NANO</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.qualcomm.robotcore.util.ElapsedTime.dMILLIS_IN_NANO">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="lMILLIS_IN_NANO">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>lMILLIS_IN_NANO</h4>
<pre>public static final long lMILLIS_IN_NANO</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.qualcomm.robotcore.util.ElapsedTime.lMILLIS_IN_NANO">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ElapsedTime()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ElapsedTime</h4>
<pre>public ElapsedTime()</pre>
<div class="block">Constructor
<p>
Starts the timer</div>
</li>
</ul>
<a name="ElapsedTime(long)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ElapsedTime</h4>
<pre>public ElapsedTime(long startTime)</pre>
<div class="block">Constructor
<p>
Starts timer with a pre-set time</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>startTime</code> - pre set time</dd></dl>
</li>
</ul>
<a name="ElapsedTime(com.qualcomm.robotcore.util.ElapsedTime.Resolution)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ElapsedTime</h4>
<pre>public ElapsedTime(<a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util">ElapsedTime.Resolution</a> resolution)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="reset()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>reset</h4>
<pre>public void reset()</pre>
<div class="block">Reset the start time to now</div>
</li>
</ul>
<a name="startTime()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>startTime</h4>
<pre>public double startTime()</pre>
<div class="block">Get the relative start time</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>relative start time</dd></dl>
</li>
</ul>
<a name="time()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>time</h4>
<pre>public double time()</pre>
<div class="block">How many seconds since the start time. Nanosecond accuracy.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>time</dd></dl>
</li>
</ul>
<a name="log(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>log</h4>
<pre>public void log(java.lang.String label)</pre>
<div class="block">Log a message stating how long the timer has been running</div>
</li>
</ul>
<a name="toString()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<div class="block">Return a string stating the number of seconds that have passed</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/qualcomm/robotcore/util/DifferentialControlLoopCoefficients.html" title="class in com.qualcomm.robotcore.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/qualcomm/robotcore/util/ElapsedTime.Resolution.html" title="enum in com.qualcomm.robotcore.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/qualcomm/robotcore/util/ElapsedTime.html" target="_top">Frames</a></li>
<li><a href="ElapsedTime.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| mit |
TukekeSoft/jacos2d-x | src/cocos2dx/platform/mac/CCApplication.h | 2853 | /****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CC_APPLICATION_MAC_H__
#define __CC_APPLICATION_MAC_H__
#include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
#include <string>
NS_CC_BEGIN
class CC_DLL CCApplication : public CCApplicationProtocol
{
public:
CCApplication();
virtual ~CCApplication();
/**
@brief Callback by CCDirector for limit FPS.
@interval The time, which expressed in second in second, between current frame and next.
*/
virtual void setAnimationInterval(double interval);
/**
@brief Get status bar rectangle in EGLView window.
*/
/**
@brief Run the message loop.
*/
int run();
/**
@brief Get current applicaiton instance.
@return Current application instance pointer.
*/
static CCApplication* sharedApplication();
/**
@brief Get current language config
@return Current language config
*/
virtual ccLanguageType getCurrentLanguage();
/**
@brief Get target platform
*/
virtual TargetPlatform getTargetPlatform();
/* set the Resource root path */
void setResourceRootPath(const std::string& rootResDir);
/* get the Resource root path */
const std::string& getResourceRootPath(void);
void setStartupScriptFilename(const std::string& startupScriptFile);
const std::string& getStartupScriptFilename(void);
protected:
static CCApplication * sm_pSharedApplication;
std::string m_resourceRootPath;
std::string m_startupScriptFilename;
};
NS_CC_END
#endif // end of __CC_APPLICATION_MAC_H__;
| mit |
heladio/my-blog | themes/chunk/templates/disqus_script.html | 407 | <script type="text/javascript">
var disqus_shortname = '{{ DISQUS_SITENAME }}';
(function () {
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
| mit |
john-bixly/Morsel | app/vendor/lodash-amd/compat/collections/map.js | 2696 | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
define(['../internals/baseEach', '../functions/createCallback', '../objects/isArray'], function(baseEach, createCallback, isArray) {
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(characters, 'name');
* // => ['barney', 'fred']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = createCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
baseEach(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
return map;
});
| mit |
davehorton/drachtio-server | deps/boost_1_77_0/libs/histogram/examples/guide_histogram_serialization.cpp | 1128 | // Copyright 2015-2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//[ guide_histogram_serialization
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/histogram.hpp>
#include <boost/histogram/serialization.hpp> // includes serialization code
#include <cassert>
#include <sstream>
int main() {
using namespace boost::histogram;
auto a = make_histogram(axis::regular<>(3, -1.0, 1.0, "axis 0"),
axis::integer<>(0, 2, "axis 1"));
a(0.5, 1);
std::string buf; // to hold persistent representation
// store histogram
{
std::ostringstream os;
boost::archive::text_oarchive oa(os);
oa << a;
buf = os.str();
}
auto b = decltype(a)(); // create a default-constructed second histogram
assert(b != a); // b is empty, a is not
// load histogram
{
std::istringstream is(buf);
boost::archive::text_iarchive ia(is);
ia >> b;
}
assert(b == a); // now b is equal to a
}
//]
| mit |
saberyounis/Sonata-Project | vendor/stephpy/timeline-bundle/DependencyInjection/SpyTimelineExtension.php | 8842 | <?php
namespace Spy\TimelineBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Config\Definition\Processor;
class SpyTimelineExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$configuration = new Configuration();
$config = $processor->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/services'));
$loader->load('filter.xml');
$loader->load('notification.xml');
$loader->load('paginator.xml');
$loader->load('resolve_component.xml');
$loader->load('result_builder.xml');
$loader->load('spread.xml');
$loader->load('twig.xml');
$driver = null;
if (isset($config['drivers'])) {
if (isset($config['drivers']['orm'])) {
$this->loadORMDriver($container, $loader, $config['drivers']['orm']);
$driver = 'orm';
} elseif (isset($config['drivers']['odm'])) {
$this->loadODMDriver($container, $loader, $config['drivers']['odm']);
$driver = 'odm';
} elseif (isset($config['drivers']['redis'])) {
$this->loadRedisDriver($container, $loader, $config['drivers']['redis']);
$driver = 'redis';
}
}
if (!$driver) {
$timelineManager = $config['timeline_manager'];
$actionManager = $config['action_manager'];
} else {
$timelineManager = isset($config['timeline_manager']) ? $config['timeline_manager'] : sprintf('spy_timeline.timeline_manager.%s', $driver);
$actionManager = isset($config['action_manager']) ? $config['action_manager'] : sprintf('spy_timeline.action_manager.%s', $driver);
}
$container->setAlias('spy_timeline.timeline_manager', $timelineManager);
$container->setAlias('spy_timeline.action_manager', $actionManager);
// pager
if (isset($config['paginator']) && !empty($config['paginator'])) {
$paginator = $config['paginator'];
} else {
$paginator = sprintf('spy_timeline.pager.%s', $driver);
}
// filters
$filters = isset($config['filters']) ? $config['filters'] : array();
$filterManager = $container->getDefinition('spy_timeline.filter.manager');
if (isset($filters['duplicate_key'])) {
$filter = $filters['duplicate_key'];
$service = $container->getDefinition($filter['service']);
$service->addMethodCall('setPriority', array($filter['priority']));
$filterManager->addMethodCall('add', array($service));
}
if (isset($filters['data_hydrator'])) {
$filter = $filters['data_hydrator'];
$service = $container->getDefinition($filter['service']);
$service->addArgument($filter['filter_unresolved']);
$service->addMethodCall('setPriority', array($filter['priority']));
$container->setParameter('spy_timeline.filter.data_hydrator.locators_config', $filter['locators']);
$filterManager->addMethodCall('add', array($service));
}
// result builder
$definition = $container->getDefinition('spy_timeline.result_builder');
$definition->addArgument($container->getDefinition(sprintf('spy_timeline.query_executor.%s', $driver)));
$definition->addArgument($filterManager);
if ($paginator) {
$definition->addMethodCall('setPager', array($container->getDefinition($paginator)));
}
// spreads
$container->setAlias('spy_timeline.spread.deployer', $config['spread']['deployer']);
$container->setParameter('spy_timeline.spread.deployer.delivery', $config['spread']['delivery']);
$container->setParameter('spy_timeline.spread.on_subject', $config['spread']['on_subject']);
$container->setParameter('spy_timeline.spread.on_global_context', $config['spread']['on_global_context']);
$container->setParameter('spy_timeline.spread.deployer.batch_size', $config['spread']['batch_size']);
// notifiers
$notifiers = $config['notifiers'];
$definition = $container->getDefinition($config['spread']['deployer']);
foreach ($notifiers as $notifier) {
$definition->addMethodCall('addNotifier', array(new Reference($notifier)));
}
//twig
$render = $config['render'];
$container->setParameter('spy_timeline.render.path', $render['path']);
$container->setParameter('spy_timeline.render.fallback', $render['fallback']);
$container->setParameter('spy_timeline.render.i18n.fallback', isset($render['i18n']) && isset($render['i18n']['fallback']) ? $render['i18n']['fallback'] : null);
$container->setParameter('spy_timeline.twig.resources', $render['resources']);
// query_builder
$queryBuilder = $config['query_builder'];
$container->setParameter('spy_timeline.query_builder.factory.class', $queryBuilder['classes']['factory']);
$container->setParameter('spy_timeline.query_builder.asserter.class', $queryBuilder['classes']['asserter']);
$container->setParameter('spy_timeline.query_builder.operator.class', $queryBuilder['classes']['operator']);
// resolve_component
$resolveComponent = $config['resolve_component'];
$container->setAlias('spy_timeline.resolve_component.resolver', $resolveComponent['resolver']);
// sets a parameter which we use in the addRegistryCompilerPass (there should be a cleaner way)
if ($resolveComponent['resolver'] === 'spy_timeline.resolve_component.doctrine') {
$container->setParameter('spy_timeline.resolve_component.doctrine_registries', true);
}
}
private function loadORMDriver($container, $loader, $config)
{
$classes = isset($config['classes']) ? $config['classes'] : array();
$parameters = array(
'timeline', 'action', 'component', 'action_component',
);
foreach ($parameters as $parameter) {
if (isset($classes[$parameter])) {
$container->setParameter(sprintf('spy_timeline.class.%s', $parameter), $classes[$parameter]);
}
}
$container->setAlias('spy_timeline.driver.object_manager', $config['object_manager']);
$loader->load('driver/orm.xml');
if ($config['post_load_listener']) {
$loader->load('driver/doctrine/orm_listener.xml');
}
if (isset($classes['query_builder'])) {
$container->setParameter('spy_timeline.query_builder.class', $classes['query_builder']);
}
$loader->load('query_builder.xml');
$container->setAlias('spy_timeline.query_builder', 'spy_timeline.query_builder.orm');
}
private function loadODMDriver($container, $loader, $config)
{
$classes = isset($config['classes']) ? $config['classes'] : array();
$parameters = array(
'timeline', 'action', 'component', 'action_component',
);
foreach ($parameters as $parameter) {
if (isset($classes[$parameter])) {
$container->setParameter(sprintf('spy_timeline.class.%s', $parameter), $classes[$parameter]);
}
}
$container->setAlias('spy_timeline.driver.object_manager', $config['object_manager']);
$loader->load('driver/odm.xml');
if ($config['post_load_listener']) {
$loader->load('driver/doctrine/odm_listener.xml');
}
}
private function loadRedisDriver($container, $loader, $config)
{
$classes = isset($config['classes']) ? $config['classes'] : array();
$parameters = array(
'action', 'component', 'action_component',
);
foreach ($parameters as $parameter) {
if (isset($classes[$parameter])) {
$container->setParameter(sprintf('spy_timeline.class.%s', $parameter), $classes[$parameter]);
}
}
$container->setParameter('spy_timeline.driver.redis.pipeline', $config['pipeline']);
$container->setParameter('spy_timeline.driver.redis.prefix', $config['prefix']);
$container->setAlias('spy_timeline.driver.redis.client', $config['client']);
$loader->load('driver/redis.xml');
}
}
| mit |
wemcdonald/reactable | src/reactable.global.js | 57 | window.Reactable = require('../build/reactable.common');
| mit |
pfnet/chainer | chainer/backends/intel64.py | 5920 | from __future__ import absolute_import
import numpy
import chainer
from chainer import _backend
from chainer.backends import _cpu
from chainer.configuration import config
_ideep_version = None
_error = None
try:
import ideep4py as ideep # NOQA
from ideep4py import mdarray # type: ignore # NOQA
_ideep_version = 2 if hasattr(ideep, '__version__') else 1
except ImportError as e:
_error = e
_ideep_version = None
class mdarray(object): # type: ignore
pass # for type testing
class Intel64Device(_backend.Device):
"""Device for Intel64 (Intel Architecture) backend with iDeep"""
xp = numpy
name = '@intel64'
supported_array_types = (numpy.ndarray, mdarray)
__hash__ = _backend.Device.__hash__
def __init__(self):
check_ideep_available()
super(Intel64Device, self).__init__()
@staticmethod
def from_array(array):
if isinstance(array, mdarray):
return Intel64Device()
return None
def __eq__(self, other):
return isinstance(other, Intel64Device)
def __repr__(self):
return '<{}>'.format(self.__class__.__name__)
def send_array(self, array):
if isinstance(array, ideep.mdarray):
return array
if not isinstance(array, numpy.ndarray):
array = _cpu._to_cpu(array) # to numpy.ndarray
if (isinstance(array, numpy.ndarray) and
array.ndim in (1, 2, 4) and
0 not in array.shape):
# TODO(kmaehashi): Remove ndim validation once iDeep has fixed.
# Currently iDeep only supports (1, 2, 4)-dim arrays.
# Note that array returned from `ideep.array` may not be an
# iDeep mdarray, e.g., when the dtype is not float32.
array = ideep.array(array, itype=ideep.wgt_array)
return array
def is_array_supported(self, array):
return isinstance(array, (numpy.ndarray, mdarray))
# ------------------------------------------------------------------------------
# ideep configuration
# ------------------------------------------------------------------------------
_SHOULD_USE_IDEEP = {
'==always': {'always': True, 'auto': False, 'never': False},
'>=auto': {'always': True, 'auto': True, 'never': False},
}
def is_ideep_available():
"""Returns if iDeep is available.
Returns:
bool: ``True`` if the supported version of iDeep is installed.
"""
return _ideep_version is not None and _ideep_version == 2
def check_ideep_available():
"""Checks if iDeep is available.
When iDeep is correctly set up, nothing happens.
Otherwise it raises ``RuntimeError``.
"""
if _ideep_version is None:
# If the error is missing shared object, append a message to
# redirect to the ideep website.
msg = str(_error)
if 'cannot open shared object file' in msg:
msg += ('\n\nEnsure iDeep requirements are satisfied: '
'https://github.com/intel/ideep')
raise RuntimeError(
'iDeep is not available.\n'
'Reason: {}: {}'.format(type(_error).__name__, msg))
elif _ideep_version != 2:
raise RuntimeError(
'iDeep is not available.\n'
'Reason: Unsupported iDeep version ({})'.format(_ideep_version))
def should_use_ideep(level):
"""Determines if we should use iDeep.
This function checks ``chainer.config.use_ideep`` and availability
of ``ideep4py`` package.
Args:
level (str): iDeep use level. It must be either ``'==always'`` or
``'>=auto'``. ``'==always'`` indicates that the ``use_ideep``
config must be ``'always'`` to use iDeep.
Returns:
bool: ``True`` if the caller should use iDeep.
"""
if not is_ideep_available():
return False
# TODO(niboshi):
# Add lowest_version argument and compare with ideep version.
# Currently ideep does not provide a way to retrieve its version.
if level not in _SHOULD_USE_IDEEP:
raise ValueError('invalid iDeep use level: %s '
'(must be either of "==always" or ">=auto")' %
repr(level))
flags = _SHOULD_USE_IDEEP[level]
use_ideep = config.use_ideep
if use_ideep not in flags:
raise ValueError('invalid use_ideep configuration: %s '
'(must be either of "always", "auto", or "never")' %
repr(use_ideep))
return flags[use_ideep]
def inputs_all_ready(inputs, supported_ndim=(2, 4)):
"""Checks if input arrays are supported for an iDeep primitive.
Before calling an iDeep primitive (e.g., ``ideep4py.linear.Forward``), you
need to make sure that all input arrays are ready for the primitive by
calling this function.
Information to be checked includes array types, dimesions and data types.
The function checks ``inputs`` info and ``supported_ndim``.
Inputs to be tested can be any of ``Variable``, ``numpy.ndarray`` or
``ideep4py.mdarray``. However, all inputs to iDeep primitives must be
``ideep4py.mdarray``. Callers of iDeep primitives are responsible of
converting all inputs to ``ideep4py.mdarray``.
Args:
inputs (sequence of arrays or variables):
Inputs to be checked.
supported_ndim (tuple of ints):
Supported ndim values for the iDeep primitive.
Returns:
bool: ``True`` if all conditions meet.
"""
def _is_supported_array_type(a):
return isinstance(a, ideep.mdarray) or ideep.check_type([a])
if not is_ideep_available():
return False
inputs = [x.data if isinstance(x, chainer.variable.Variable)
else x for x in inputs]
return (ideep.check_ndim(inputs, supported_ndim)
and all([_is_supported_array_type(a) for a in inputs]))
| mit |
netcosports/material-calendarview | library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java | 5089 | package com.prolificinteractive.materialcalendarview;
import android.animation.Animator;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.ViewPropertyAnimator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.TextView;
import com.prolificinteractive.materialcalendarview.format.TitleFormatter;
class TitleChanger {
public static final int DEFAULT_ANIMATION_DELAY = 400;
public static final int DEFAULT_Y_TRANSLATION_DP = 20;
private final TextView title;
private TitleFormatter titleFormatter;
private final int animDelay;
private final int animDuration;
private final int translate;
private final Interpolator interpolator = new DecelerateInterpolator(2f);
private int orientation = MaterialCalendarView.VERTICAL;
private long lastAnimTime = 0;
private CalendarDay previousMonth = null;
public TitleChanger(TextView title) {
this.title = title;
Resources res = title.getResources();
animDelay = DEFAULT_ANIMATION_DELAY;
animDuration = res.getInteger(android.R.integer.config_shortAnimTime) / 2;
translate = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, DEFAULT_Y_TRANSLATION_DP, res.getDisplayMetrics()
);
}
public void change(final CalendarDay currentMonth) {
long currentTime = System.currentTimeMillis();
if (currentMonth == null) {
return;
}
if (TextUtils.isEmpty(title.getText()) || (currentTime - lastAnimTime) < animDelay) {
doChange(currentTime, currentMonth, false);
}
if (currentMonth.equals(previousMonth) ||
(currentMonth.getMonth() == previousMonth.getMonth()
&& currentMonth.getYear() == previousMonth.getYear())) {
return;
}
doChange(currentTime, currentMonth, true);
}
private void doChange(final long now, final CalendarDay currentMonth, boolean animate) {
title.animate().cancel();
doTranslation(title, 0);
title.setAlpha(1);
lastAnimTime = now;
final CharSequence newTitle = titleFormatter.format(currentMonth);
if (!animate) {
title.setText(newTitle);
} else {
final int translation = translate * (previousMonth.isBefore(currentMonth) ? 1 : -1);
final ViewPropertyAnimator viewPropertyAnimator = title.animate();
if (orientation == MaterialCalendarView.HORIZONTAL) {
viewPropertyAnimator.translationX(translation * -1);
} else {
viewPropertyAnimator.translationY(translation * -1);
}
viewPropertyAnimator
.alpha(0)
.setDuration(animDuration)
.setInterpolator(interpolator)
.setListener(new AnimatorListener() {
@Override
public void onAnimationCancel(Animator animator) {
doTranslation(title, 0);
title.setAlpha(1);
}
@Override
public void onAnimationEnd(Animator animator) {
title.setText(newTitle);
doTranslation(title, translation);
final ViewPropertyAnimator viewPropertyAnimator = title.animate();
if (orientation == MaterialCalendarView.HORIZONTAL) {
viewPropertyAnimator.translationX(0);
} else {
viewPropertyAnimator.translationY(0);
}
viewPropertyAnimator
.alpha(1)
.setDuration(animDuration)
.setInterpolator(interpolator)
.setListener(new AnimatorListener())
.start();
}
}).start();
}
previousMonth = currentMonth;
}
private void doTranslation(final TextView title, final int translate) {
if (orientation == MaterialCalendarView.HORIZONTAL) {
title.setTranslationX(translate);
} else {
title.setTranslationY(translate);
}
}
public TitleFormatter getTitleFormatter() {
return titleFormatter;
}
public void setTitleFormatter(TitleFormatter titleFormatter) {
this.titleFormatter = titleFormatter;
}
public void setOrientation(int orientation) {
this.orientation = orientation;
}
public int getOrientation() {
return orientation;
}
public void setPreviousMonth(CalendarDay previousMonth) {
this.previousMonth = previousMonth;
}
}
| mit |
h-iwata/MultiplayPaint | proj.ios_mac/Photon-iOS_SDK/Demos/etc-bin/cocos2dx/cocos2dx/script_support/CCScriptSupport.cpp | 5005 | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCScriptSupport.h"
#include "CCScheduler.h"
bool CC_DLL cc_assert_script_compatible(const char *msg)
{
cocos2d::CCScriptEngineProtocol* pEngine = cocos2d::CCScriptEngineManager::sharedManager()->getScriptEngine();
if (pEngine && pEngine->handleAssert(msg))
{
return true;
}
return false;
}
NS_CC_BEGIN
// #pragma mark -
// #pragma mark CCScriptHandlerEntry
CCScriptHandlerEntry* CCScriptHandlerEntry::create(int nHandler)
{
CCScriptHandlerEntry* entry = new CCScriptHandlerEntry(nHandler);
entry->autorelease();
return entry;
}
CCScriptHandlerEntry::~CCScriptHandlerEntry(void)
{
if (m_nHandler != 0)
{
CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nHandler);
m_nHandler = 0;
}
}
// #pragma mark -
// #pragma mark CCSchedulerScriptHandlerEntry
CCSchedulerScriptHandlerEntry* CCSchedulerScriptHandlerEntry::create(int nHandler, float fInterval, bool bPaused)
{
CCSchedulerScriptHandlerEntry* pEntry = new CCSchedulerScriptHandlerEntry(nHandler);
pEntry->init(fInterval, bPaused);
pEntry->autorelease();
return pEntry;
}
bool CCSchedulerScriptHandlerEntry::init(float fInterval, bool bPaused)
{
m_pTimer = new CCTimer();
m_pTimer->initWithScriptHandler(m_nHandler, fInterval);
m_pTimer->autorelease();
m_pTimer->retain();
m_bPaused = bPaused;
LUALOG("[LUA] ADD script schedule: %d, entryID: %d", m_nHandler, m_nEntryId);
return true;
}
CCSchedulerScriptHandlerEntry::~CCSchedulerScriptHandlerEntry(void)
{
m_pTimer->release();
LUALOG("[LUA] DEL script schedule %d, entryID: %d", m_nHandler, m_nEntryId);
}
// #pragma mark -
// #pragma mark CCTouchScriptHandlerEntry
CCTouchScriptHandlerEntry* CCTouchScriptHandlerEntry::create(int nHandler,
bool bIsMultiTouches,
int nPriority,
bool bSwallowsTouches)
{
CCTouchScriptHandlerEntry* pEntry = new CCTouchScriptHandlerEntry(nHandler);
pEntry->init(bIsMultiTouches, nPriority, bSwallowsTouches);
pEntry->autorelease();
return pEntry;
}
CCTouchScriptHandlerEntry::~CCTouchScriptHandlerEntry(void)
{
if (m_nHandler != 0)
{
CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nHandler);
LUALOG("[LUA] Remove touch event handler: %d", m_nHandler);
m_nHandler = 0;
}
}
bool CCTouchScriptHandlerEntry::init(bool bIsMultiTouches, int nPriority, bool bSwallowsTouches)
{
m_bIsMultiTouches = bIsMultiTouches;
m_nPriority = nPriority;
m_bSwallowsTouches = bSwallowsTouches;
return true;
}
// #pragma mark -
// #pragma mark CCScriptEngineManager
static CCScriptEngineManager* s_pSharedScriptEngineManager = NULL;
CCScriptEngineManager::~CCScriptEngineManager(void)
{
removeScriptEngine();
}
void CCScriptEngineManager::setScriptEngine(CCScriptEngineProtocol *pScriptEngine)
{
removeScriptEngine();
m_pScriptEngine = pScriptEngine;
}
void CCScriptEngineManager::removeScriptEngine(void)
{
if (m_pScriptEngine)
{
delete m_pScriptEngine;
m_pScriptEngine = NULL;
}
}
CCScriptEngineManager* CCScriptEngineManager::sharedManager(void)
{
if (!s_pSharedScriptEngineManager)
{
s_pSharedScriptEngineManager = new CCScriptEngineManager();
}
return s_pSharedScriptEngineManager;
}
void CCScriptEngineManager::purgeSharedManager(void)
{
if (s_pSharedScriptEngineManager)
{
delete s_pSharedScriptEngineManager;
s_pSharedScriptEngineManager = NULL;
}
}
NS_CC_END
| mit |
sufuf3/cdnjs | ajax/libs/ag-grid/21.0.0/lib/dragAndDrop/dragService.js | 13765 | /**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v20.2.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../context/context");
var logger_1 = require("../logger");
var eventService_1 = require("../eventService");
var events_1 = require("../events");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var columnApi_1 = require("../columnController/columnApi");
var gridApi_1 = require("../gridApi");
var utils_1 = require("../utils");
/** Adds drag listening onto an element. In ag-Grid this is used twice, first is resizing columns,
* second is moving the columns and column groups around (ie the 'drag' part of Drag and Drop. */
var DragService = /** @class */ (function () {
function DragService() {
this.onMouseUpListener = this.onMouseUp.bind(this);
this.onMouseMoveListener = this.onMouseMove.bind(this);
this.onTouchEndListener = this.onTouchUp.bind(this);
this.onTouchMoveListener = this.onTouchMove.bind(this);
this.dragEndFunctions = [];
this.dragSources = [];
}
DragService.prototype.init = function () {
this.logger = this.loggerFactory.create('DragService');
};
DragService.prototype.destroy = function () {
this.dragSources.forEach(this.removeListener.bind(this));
this.dragSources.length = 0;
};
DragService.prototype.removeListener = function (dragSourceAndListener) {
var element = dragSourceAndListener.dragSource.eElement;
var mouseDownListener = dragSourceAndListener.mouseDownListener;
element.removeEventListener('mousedown', mouseDownListener);
// remove touch listener only if it exists
if (dragSourceAndListener.touchEnabled) {
var touchStartListener = dragSourceAndListener.touchStartListener;
element.removeEventListener('touchstart', touchStartListener, { passive: true });
}
};
DragService.prototype.removeDragSource = function (params) {
var dragSourceAndListener = utils_1._.find(this.dragSources, function (item) { return item.dragSource === params; });
if (!dragSourceAndListener) {
return;
}
this.removeListener(dragSourceAndListener);
utils_1._.removeFromArray(this.dragSources, dragSourceAndListener);
};
DragService.prototype.setNoSelectToBody = function (noSelect) {
var eDocument = this.gridOptionsWrapper.getDocument();
var eBody = eDocument.querySelector('body');
if (utils_1._.exists(eBody)) {
// when we drag the mouse in ag-Grid, this class gets added / removed from the body, so that
// the mouse isn't selecting text when dragging.
utils_1._.addOrRemoveCssClass(eBody, 'ag-unselectable', noSelect);
}
};
DragService.prototype.addDragSource = function (params, includeTouch) {
if (includeTouch === void 0) { includeTouch = false; }
var mouseListener = this.onMouseDown.bind(this, params);
params.eElement.addEventListener('mousedown', mouseListener);
var touchListener = null;
var suppressTouch = this.gridOptionsWrapper.isSuppressTouch();
if (includeTouch && !suppressTouch) {
touchListener = this.onTouchStart.bind(this, params);
params.eElement.addEventListener('touchstart', touchListener, { passive: false });
}
this.dragSources.push({
dragSource: params,
mouseDownListener: mouseListener,
touchStartListener: touchListener,
touchEnabled: includeTouch
});
};
// gets called whenever mouse down on any drag source
DragService.prototype.onTouchStart = function (params, touchEvent) {
var _this = this;
this.currentDragParams = params;
this.dragging = false;
var touch = touchEvent.touches[0];
this.touchLastTime = touch;
this.touchStart = touch;
touchEvent.preventDefault();
// we temporally add these listeners, for the duration of the drag, they
// are removed in touch end handling.
params.eElement.addEventListener('touchmove', this.onTouchMoveListener, { passive: true });
params.eElement.addEventListener('touchend', this.onTouchEndListener, { passive: true });
params.eElement.addEventListener('touchcancel', this.onTouchEndListener, { passive: true });
this.dragEndFunctions.push(function () {
params.eElement.removeEventListener('touchmove', _this.onTouchMoveListener, { passive: true });
params.eElement.removeEventListener('touchend', _this.onTouchEndListener, { passive: true });
params.eElement.removeEventListener('touchcancel', _this.onTouchEndListener, { passive: true });
});
// see if we want to start dragging straight away
if (params.dragStartPixels === 0) {
this.onCommonMove(touch, this.touchStart);
}
};
// gets called whenever mouse down on any drag source
DragService.prototype.onMouseDown = function (params, mouseEvent) {
var _this = this;
// we ignore when shift key is pressed. this is for the range selection, as when
// user shift-clicks a cell, this should not be interpreted as the start of a drag.
// if (mouseEvent.shiftKey) { return; }
if (params.skipMouseEvent) {
if (params.skipMouseEvent(mouseEvent)) {
return;
}
}
// if there are two elements with parent / child relationship, and both are draggable,
// when we drag the child, we should NOT drag the parent. an example of this is row moving
// and range selection - row moving should get preference when use drags the rowDrag component.
if (mouseEvent._alreadyProcessedByDragService) {
return;
}
mouseEvent._alreadyProcessedByDragService = true;
// only interested in left button clicks
if (mouseEvent.button !== 0) {
return;
}
this.currentDragParams = params;
this.dragging = false;
this.mouseEventLastTime = mouseEvent;
this.mouseStartEvent = mouseEvent;
var eDocument = this.gridOptionsWrapper.getDocument();
// we temporally add these listeners, for the duration of the drag, they
// are removed in mouseup handling.
eDocument.addEventListener('mousemove', this.onMouseMoveListener);
eDocument.addEventListener('mouseup', this.onMouseUpListener);
this.dragEndFunctions.push(function () {
eDocument.removeEventListener('mousemove', _this.onMouseMoveListener);
eDocument.removeEventListener('mouseup', _this.onMouseUpListener);
});
//see if we want to start dragging straight away
if (params.dragStartPixels === 0) {
this.onMouseMove(mouseEvent);
}
};
// returns true if the event is close to the original event by X pixels either vertically or horizontally.
// we only start dragging after X pixels so this allows us to know if we should start dragging yet.
DragService.prototype.isEventNearStartEvent = function (currentEvent, startEvent) {
// by default, we wait 4 pixels before starting the drag
var dragStartPixels = this.currentDragParams.dragStartPixels;
var requiredPixelDiff = utils_1._.exists(dragStartPixels) ? dragStartPixels : 4;
return utils_1._.areEventsNear(currentEvent, startEvent, requiredPixelDiff);
};
DragService.prototype.getFirstActiveTouch = function (touchList) {
for (var i = 0; i < touchList.length; i++) {
if (touchList[i].identifier === this.touchStart.identifier) {
return touchList[i];
}
}
return null;
};
DragService.prototype.onCommonMove = function (currentEvent, startEvent) {
if (!this.dragging) {
// if mouse hasn't travelled from the start position enough, do nothing
if (!this.dragging && this.isEventNearStartEvent(currentEvent, startEvent)) {
return;
}
this.dragging = true;
var event_1 = {
type: events_1.Events.EVENT_DRAG_STARTED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_1);
this.currentDragParams.onDragStart(startEvent);
this.setNoSelectToBody(true);
}
this.currentDragParams.onDragging(currentEvent);
};
DragService.prototype.onTouchMove = function (touchEvent) {
var touch = this.getFirstActiveTouch(touchEvent.touches);
if (!touch) {
return;
}
// this.___statusPanel.setInfoText(Math.random() + ' onTouchMove preventDefault stopPropagation');
// if we don't preview default, then the browser will try and do it's own touch stuff,
// like do 'back button' (chrome does this) or scroll the page (eg drag column could be confused
// with scroll page in the app)
// touchEvent.preventDefault();
this.onCommonMove(touch, this.touchStart);
};
// only gets called after a mouse down - as this is only added after mouseDown
// and is removed when mouseUp happens
DragService.prototype.onMouseMove = function (mouseEvent) {
this.onCommonMove(mouseEvent, this.mouseStartEvent);
};
DragService.prototype.onTouchUp = function (touchEvent) {
var touch = this.getFirstActiveTouch(touchEvent.changedTouches);
// i haven't worked this out yet, but there is no matching touch
// when we get the touch up event. to get around this, we swap in
// the last touch. this is a hack to 'get it working' while we
// figure out what's going on, why we are not getting a touch in
// current event.
if (!touch) {
touch = this.touchLastTime;
}
// if mouse was left up before we started to move, then this is a tap.
// we check this before onUpCommon as onUpCommon resets the dragging
// let tap = !this.dragging;
// let tapTarget = this.currentDragParams.eElement;
this.onUpCommon(touch);
// if tap, tell user
// console.log(`${Math.random()} tap = ${tap}`);
// if (tap) {
// tapTarget.click();
// }
};
DragService.prototype.onMouseUp = function (mouseEvent) {
this.onUpCommon(mouseEvent);
};
DragService.prototype.onUpCommon = function (eventOrTouch) {
if (this.dragging) {
this.dragging = false;
this.currentDragParams.onDragStop(eventOrTouch);
var event_2 = {
type: events_1.Events.EVENT_DRAG_STOPPED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_2);
}
this.setNoSelectToBody(false);
this.mouseStartEvent = null;
this.mouseEventLastTime = null;
this.touchStart = null;
this.touchLastTime = null;
this.currentDragParams = null;
this.dragEndFunctions.forEach(function (func) { return func(); });
this.dragEndFunctions.length = 0;
};
__decorate([
context_1.Autowired('loggerFactory'),
__metadata("design:type", logger_1.LoggerFactory)
], DragService.prototype, "loggerFactory", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], DragService.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], DragService.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('columnApi'),
__metadata("design:type", columnApi_1.ColumnApi)
], DragService.prototype, "columnApi", void 0);
__decorate([
context_1.Autowired('gridApi'),
__metadata("design:type", gridApi_1.GridApi)
], DragService.prototype, "gridApi", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], DragService.prototype, "init", null);
__decorate([
context_1.PreDestroy,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], DragService.prototype, "destroy", null);
DragService = __decorate([
context_1.Bean('dragService')
], DragService);
return DragService;
}());
exports.DragService = DragService;
| mit |
Kunstmaan/KunstmaanBundlesCMS | src/Kunstmaan/AdminBundle/Helper/Menu/SettingsMenuAdaptor.php | 2981 | <?php
namespace Kunstmaan\AdminBundle\Helper\Menu;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* SettingsMenuAdaptor to add the Settings MenuItem to the top menu and build the Settings tree
*/
class SettingsMenuAdaptor implements MenuAdaptorInterface
{
/** @var AuthorizationCheckerInterface */
private $authorizationChecker;
/** @var bool */
private $isEnabledVersionChecker;
/** @var bool */
private $exceptionLoggingEnabled;
/**
* @param bool $isEnabledVersionChecker
*/
public function __construct(AuthorizationCheckerInterface $authorizationChecker, $isEnabledVersionChecker, bool $exceptionLoggingEnabled = true)
{
$this->authorizationChecker = $authorizationChecker;
$this->isEnabledVersionChecker = (bool) $isEnabledVersionChecker;
$this->exceptionLoggingEnabled = $exceptionLoggingEnabled;
}
public function adaptChildren(MenuBuilder $menu, array &$children, MenuItem $parent = null, Request $request = null)
{
if (\is_null($parent)) {
$menuItem = new TopMenuItem($menu);
$menuItem
->setRoute('KunstmaanAdminBundle_settings')
->setLabel('settings.title')
->setUniqueId('settings')
->setParent($parent)
->setRole('settings');
if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) {
$menuItem->setActive(true);
}
$children[] = $menuItem;
}
if (!\is_null($parent) && 'KunstmaanAdminBundle_settings' == $parent->getRoute()) {
if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN') && $this->isEnabledVersionChecker) {
$menuItem = new MenuItem($menu);
$menuItem
->setRoute('KunstmaanAdminBundle_settings_bundle_version')
->setLabel('settings.version.bundle')
->setUniqueId('bundle_versions')
->setParent($parent);
if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) {
$menuItem->setActive(true);
}
$children[] = $menuItem;
}
if ($this->exceptionLoggingEnabled) {
$menuItem = new MenuItem($menu);
$menuItem
->setRoute('kunstmaanadminbundle_admin_exception')
->setLabel('settings.exceptions.title')
->setUniqueId('exceptions')
->setParent($parent);
if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) {
$menuItem->setActive(true);
$parent->setActive(true);
}
$children[] = $menuItem;
}
}
}
}
| mit |
glennrub/micropython | ports/samd/main.c | 3125 | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* 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 "py/compile.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/mperrno.h"
#include "py/stackctrl.h"
#include "shared/runtime/gchelper.h"
#include "shared/runtime/pyexec.h"
extern uint8_t _sstack, _estack, _sheap, _eheap;
void samd_main(void) {
mp_stack_set_top(&_estack);
mp_stack_set_limit(&_estack - &_sstack - 1024);
for (;;) {
gc_init(&_sheap, &_eheap);
mp_init();
// Execute _boot.py to set up the filesystem.
pyexec_frozen_module("_boot.py");
// Execute user scripts.
pyexec_file_if_exists("boot.py");
pyexec_file_if_exists("main.py");
for (;;) {
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
if (pyexec_raw_repl() != 0) {
break;
}
} else {
if (pyexec_friendly_repl() != 0) {
break;
}
}
}
mp_printf(MP_PYTHON_PRINTER, "MPY: soft reboot\n");
gc_sweep_all();
mp_deinit();
}
}
void gc_collect(void) {
gc_collect_start();
gc_helper_collect_regs_and_stack();
gc_collect_end();
}
/*
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
mp_raise_OSError(MP_ENOENT);
}
*/
#if !MICROPY_VFS
mp_import_stat_t mp_import_stat(const char *path) {
return MP_IMPORT_STAT_NO_EXIST;
}
mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
#endif
void nlr_jump_fail(void *val) {
for (;;) {
}
}
void abort(void) {
for (;;) {
}
}
#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
mp_printf(MP_PYTHON_PRINTER, "Assertion '%s' failed, at file %s:%d\n", expr, file, line);
for (;;) {
}
}
#endif
| mit |
rsantellan/ventanas-html-proyecto | ventanas/src/AppBundle/Resources/public/admin/vendor/calculator/jquery.calculator-ca.js | 1535 | /* http://keith-wood.name/calculator.html
Catalan initialisation for the jQuery calculator extension
Written by Esteve Camps (ecamps at google dot com) June 2010. */
(function($) { // hide the namespace
$.calculator.regionalOptions['ca'] = {
decimalChar: ',',
buttonText: '...', buttonStatus: 'Obrir la calculadora',
closeText: 'Tancar', closeStatus: 'Tancar la calculadora',
useText: 'Usar', useStatus: 'Usar el valor actual',
eraseText: 'Esborrar', eraseStatus: 'Esborrar el valor actual',
backspaceText: 'BS', backspaceStatus: 'Esborrar el darrer dígit',
clearErrorText: 'CE', clearErrorStatus: 'Esborrar el darrer número',
clearText: 'CA', clearStatus: 'Reiniciar el càlcul',
memClearText: 'MC', memClearStatus: 'Esborrar la memòria',
memRecallText: 'MR', memRecallStatus: 'Recuperar el valor de la memòria',
memStoreText: 'MS', memStoreStatus: 'Guardar el valor a la memòria',
memAddText: 'M+', memAddStatus: 'Afegir a la memòria',
memSubtractText: 'M-', memSubtractStatus: 'Treure de la memòria',
base2Text: 'Bin', base2Status: 'Canviar al mode Binari',
base8Text: 'Oct', base8Status: 'Canviar al mode Octal',
base10Text: 'Dec', base10Status: 'Canviar al mode Decimal',
base16Text: 'Hex', base16Status: 'Canviar al mode Hexadecimal',
degreesText: 'Deg', degreesStatus: 'Canviar al mode Graus',
radiansText: 'Rad', radiansStatus: 'Canviar al mode Radians',
isRTL: false};
$.calculator.setDefaults($.calculator.regionalOptions['ca']);
})(jQuery); | mit |
michalgraczyk/calculus | web/js/tiny_mce/js/tinymce/classes/EditorCommands.js | 29362 | /**
* EditorCommands.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class enables you to add custom editor commands and it contains
* overrides for native browser commands to address various bugs and issues.
*
* @class tinymce.EditorCommands
*/
define("tinymce/EditorCommands", [
"tinymce/html/Serializer",
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/dom/ElementUtils",
"tinymce/dom/RangeUtils",
"tinymce/dom/TreeWalker"
], function(Serializer, Env, Tools, ElementUtils, RangeUtils, TreeWalker) {
// Added for compression purposes
var each = Tools.each, extend = Tools.extend;
var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode;
var isIE = Env.ie, isOldIE = Env.ie && Env.ie < 11;
var TRUE = true, FALSE = false;
return function(editor) {
var dom, selection, formatter,
commands = {state: {}, exec: {}, value: {}},
settings = editor.settings,
bookmark;
editor.on('PreInit', function() {
dom = editor.dom;
selection = editor.selection;
settings = editor.settings;
formatter = editor.formatter;
});
/**
* Executes the specified command.
*
* @method execCommand
* @param {String} command Command to execute.
* @param {Boolean} ui Optional user interface state.
* @param {Object} value Optional value for command.
* @param {Object} args Optional extra arguments to the execCommand.
* @return {Boolean} true/false if the command was found or not.
*/
function execCommand(command, ui, value, args) {
var func, customCommand, state = 0;
if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
editor.focus();
}
args = editor.fire('BeforeExecCommand', {command: command, ui: ui, value: value});
if (args.isDefaultPrevented()) {
return false;
}
customCommand = command.toLowerCase();
if ((func = commands.exec[customCommand])) {
func(customCommand, ui, value);
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
// Plugin commands
each(editor.plugins, function(p) {
if (p.execCommand && p.execCommand(command, ui, value)) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
state = true;
return false;
}
});
if (state) {
return state;
}
// Theme commands
if (editor.theme && editor.theme.execCommand && editor.theme.execCommand(command, ui, value)) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
// Browser commands
try {
state = editor.getDoc().execCommand(command, ui, value);
} catch (ex) {
// Ignore old IE errors
}
if (state) {
editor.fire('ExecCommand', {command: command, ui: ui, value: value});
return true;
}
return false;
}
/**
* Queries the current state for a command for example if the current selection is "bold".
*
* @method queryCommandState
* @param {String} command Command to check the state of.
* @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found.
*/
function queryCommandState(command) {
var func;
// Is hidden then return undefined
if (editor._isHidden()) {
return;
}
command = command.toLowerCase();
if ((func = commands.state[command])) {
return func(command);
}
// Browser commands
try {
return editor.getDoc().queryCommandState(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
return false;
}
/**
* Queries the command value for example the current fontsize.
*
* @method queryCommandValue
* @param {String} command Command to check the value of.
* @return {Object} Command value of false if it's not found.
*/
function queryCommandValue(command) {
var func;
// Is hidden then return undefined
if (editor._isHidden()) {
return;
}
command = command.toLowerCase();
if ((func = commands.value[command])) {
return func(command);
}
// Browser commands
try {
return editor.getDoc().queryCommandValue(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
}
/**
* Adds commands to the command collection.
*
* @method addCommands
* @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated.
* @param {String} type Optional type to add, defaults to exec. Can be value or state as well.
*/
function addCommands(command_list, type) {
type = type || 'exec';
each(command_list, function(callback, command) {
each(command.toLowerCase().split(','), function(command) {
commands[type][command] = callback;
});
});
}
function addCommand(command, callback, scope) {
command = command.toLowerCase();
commands.exec[command] = function(command, ui, value, args) {
return callback.call(scope || editor, ui, value, args);
};
}
/**
* Returns true/false if the command is supported or not.
*
* @method queryCommandSupported
* @param {String} command Command that we check support for.
* @return {Boolean} true/false if the command is supported or not.
*/
function queryCommandSupported(command) {
command = command.toLowerCase();
if (commands.exec[command]) {
return true;
}
// Browser commands
try {
return editor.getDoc().queryCommandSupported(command);
} catch (ex) {
// Fails sometimes see bug: 1896577
}
return false;
}
function addQueryStateHandler(command, callback, scope) {
command = command.toLowerCase();
commands.state[command] = function() {
return callback.call(scope || editor);
};
}
function addQueryValueHandler(command, callback, scope) {
command = command.toLowerCase();
commands.value[command] = function() {
return callback.call(scope || editor);
};
}
function hasCustomCommand(command) {
command = command.toLowerCase();
return !!commands.exec[command];
}
// Expose public methods
extend(this, {
execCommand: execCommand,
queryCommandState: queryCommandState,
queryCommandValue: queryCommandValue,
queryCommandSupported: queryCommandSupported,
addCommands: addCommands,
addCommand: addCommand,
addQueryStateHandler: addQueryStateHandler,
addQueryValueHandler: addQueryValueHandler,
hasCustomCommand: hasCustomCommand
});
// Private methods
function execNativeCommand(command, ui, value) {
if (ui === undefined) {
ui = FALSE;
}
if (value === undefined) {
value = null;
}
return editor.getDoc().execCommand(command, ui, value);
}
function isFormatMatch(name) {
return formatter.match(name);
}
function toggleFormat(name, value) {
formatter.toggle(name, value ? {value: value} : undefined);
editor.nodeChanged();
}
function storeSelection(type) {
bookmark = selection.getBookmark(type);
}
function restoreSelection() {
selection.moveToBookmark(bookmark);
}
// Add execCommand overrides
addCommands({
// Ignore these, added for compatibility
'mceResetDesignMode,mceBeginUndoLevel': function() {},
// Add undo manager logic
'mceEndUndoLevel,mceAddUndoLevel': function() {
editor.undoManager.add();
},
'Cut,Copy,Paste': function(command) {
var doc = editor.getDoc(), failed;
// Try executing the native command
try {
execNativeCommand(command);
} catch (ex) {
// Command failed
failed = TRUE;
}
// Present alert message about clipboard access not being available
if (failed || !doc.queryCommandSupported(command)) {
var msg = editor.translate(
"Your browser doesn't support direct access to the clipboard. " +
"Please use the Ctrl+X/C/V keyboard shortcuts instead."
);
if (Env.mac) {
msg = msg.replace(/Ctrl\+/g, '\u2318+');
}
editor.notificationManager.open({text: msg, type: 'error'});
}
},
// Override unlink command
unlink: function() {
if (selection.isCollapsed()) {
var elm = selection.getNode();
if (elm.tagName == 'A') {
editor.dom.remove(elm, true);
}
return;
}
formatter.remove("link");
},
// Override justify commands to use the text formatter engine
'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function(command) {
var align = command.substring(7);
if (align == 'full') {
align = 'justify';
}
// Remove all other alignments first
each('left,center,right,justify'.split(','), function(name) {
if (align != name) {
formatter.remove('align' + name);
}
});
if (align != 'none') {
toggleFormat('align' + align);
}
},
// Override list commands to fix WebKit bug
'InsertUnorderedList,InsertOrderedList': function(command) {
var listElm, listParent;
execNativeCommand(command);
// WebKit produces lists within block elements so we need to split them
// we will replace the native list creation logic to custom logic later on
// TODO: Remove this when the list creation logic is removed
listElm = dom.getParent(selection.getNode(), 'ol,ul');
if (listElm) {
listParent = listElm.parentNode;
// If list is within a text block then split that block
if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
storeSelection();
dom.split(listParent, listElm);
restoreSelection();
}
}
},
// Override commands to use the text formatter engine
'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
toggleFormat(command);
},
// Override commands to use the text formatter engine
'ForeColor,HiliteColor,FontName': function(command, ui, value) {
toggleFormat(command, value);
},
FontSize: function(command, ui, value) {
var fontClasses, fontSizes;
// Convert font size 1-7 to styles
if (value >= 1 && value <= 7) {
fontSizes = explode(settings.font_size_style_values);
fontClasses = explode(settings.font_size_classes);
if (fontClasses) {
value = fontClasses[value - 1] || value;
} else {
value = fontSizes[value - 1] || value;
}
}
toggleFormat(command, value);
},
RemoveFormat: function(command) {
formatter.remove(command);
},
mceBlockQuote: function() {
toggleFormat('blockquote');
},
FormatBlock: function(command, ui, value) {
return toggleFormat(value || 'p');
},
mceCleanup: function() {
var bookmark = selection.getBookmark();
editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE});
selection.moveToBookmark(bookmark);
},
mceRemoveNode: function(command, ui, value) {
var node = value || selection.getNode();
// Make sure that the body node isn't removed
if (node != editor.getBody()) {
storeSelection();
editor.dom.remove(node, TRUE);
restoreSelection();
}
},
mceSelectNodeDepth: function(command, ui, value) {
var counter = 0;
dom.getParent(selection.getNode(), function(node) {
if (node.nodeType == 1 && counter++ == value) {
selection.select(node);
return FALSE;
}
}, editor.getBody());
},
mceSelectNode: function(command, ui, value) {
selection.select(value);
},
mceInsertContent: function(command, ui, value) {
var parser, serializer, parentNode, rootNode, fragment, args;
var marker, rng, node, node2, bookmarkHtml, merge, data;
var textInlineElements = editor.schema.getTextInlineElements();
function trimOrPaddLeftRight(html) {
var rng, container, offset;
rng = selection.getRng(true);
container = rng.startContainer;
offset = rng.startOffset;
function hasSiblingText(siblingName) {
return container[siblingName] && container[siblingName].nodeType == 3;
}
if (container.nodeType == 3) {
if (offset > 0) {
html = html.replace(/^ /, ' ');
} else if (!hasSiblingText('previousSibling')) {
html = html.replace(/^ /, ' ');
}
if (offset < container.length) {
html = html.replace(/ (<br>|)$/, ' ');
} else if (!hasSiblingText('nextSibling')) {
html = html.replace(/( | )(<br>|)$/, ' ');
}
}
return html;
}
// Removes from a [b] c -> a c -> a c
function trimNbspAfterDeleteAndPaddValue() {
var rng, container, offset;
rng = selection.getRng(true);
container = rng.startContainer;
offset = rng.startOffset;
if (container.nodeType == 3 && rng.collapsed) {
if (container.data[offset] === '\u00a0') {
container.deleteData(offset, 1);
if (!/[\u00a0| ]$/.test(value)) {
value += ' ';
}
} else if (container.data[offset - 1] === '\u00a0') {
container.deleteData(offset - 1, 1);
if (!/[\u00a0| ]$/.test(value)) {
value = ' ' + value;
}
}
}
}
function markInlineFormatElements(fragment) {
if (merge) {
for (node = fragment.firstChild; node; node = node.walk(true)) {
if (textInlineElements[node.name]) {
node.attr('data-mce-new', "true");
}
}
}
}
function reduceInlineTextElements() {
if (merge) {
var root = editor.getBody(), elementUtils = new ElementUtils(dom);
each(dom.select('*[data-mce-new]'), function(node) {
node.removeAttribute('data-mce-new');
for (var testNode = node.parentNode; testNode && testNode != root; testNode = testNode.parentNode) {
if (elementUtils.compare(testNode, node)) {
dom.remove(node, true);
}
}
});
}
}
function moveSelectionToMarker(marker) {
var parentEditableFalseElm;
function getContentEditableFalseParent(node) {
var root = editor.getBody();
for (; node && node !== root; node = node.parentNode) {
if (editor.dom.getContentEditable(node) === 'false') {
return node;
}
}
return null;
}
if (!marker) {
return;
}
selection.scrollIntoView(marker);
// If marker is in cE=false then move selection to that element instead
parentEditableFalseElm = getContentEditableFalseParent(marker);
if (parentEditableFalseElm) {
dom.remove(marker);
selection.select(parentEditableFalseElm);
return;
}
// Move selection before marker and remove it
rng = dom.createRng();
// If previous sibling is a text node set the selection to the end of that node
node = marker.previousSibling;
if (node && node.nodeType == 3) {
rng.setStart(node, node.nodeValue.length);
// TODO: Why can't we normalize on IE
if (!isIE) {
node2 = marker.nextSibling;
if (node2 && node2.nodeType == 3) {
node.appendData(node2.data);
node2.parentNode.removeChild(node2);
}
}
} else {
// If the previous sibling isn't a text node or doesn't exist set the selection before the marker node
rng.setStartBefore(marker);
rng.setEndBefore(marker);
}
// Remove the marker node and set the new range
dom.remove(marker);
selection.setRng(rng);
}
if (typeof value != 'string') {
merge = value.merge;
data = value.data;
value = value.content;
}
// Check for whitespace before/after value
if (/^ | $/.test(value)) {
value = trimOrPaddLeftRight(value);
}
// Setup parser and serializer
parser = editor.parser;
serializer = new Serializer({
validate: settings.validate
}, editor.schema);
bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">​</span>';
// Run beforeSetContent handlers on the HTML to be inserted
args = {content: value, format: 'html', selection: true};
editor.fire('BeforeSetContent', args);
value = args.content;
// Add caret at end of contents if it's missing
if (value.indexOf('{$caret}') == -1) {
value += '{$caret}';
}
// Replace the caret marker with a span bookmark element
value = value.replace(/\{\$caret\}/, bookmarkHtml);
// If selection is at <body>|<p></p> then move it into <body><p>|</p>
rng = selection.getRng();
var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
var body = editor.getBody();
if (caretElement === body && selection.isCollapsed()) {
if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) {
rng = dom.createRng();
rng.setStart(body.firstChild, 0);
rng.setEnd(body.firstChild, 0);
selection.setRng(rng);
}
}
// Insert node maker where we will insert the new HTML and get it's parent
if (!selection.isCollapsed()) {
editor.getDoc().execCommand('Delete', false, null);
trimNbspAfterDeleteAndPaddValue();
}
parentNode = selection.getNode();
// Parse the fragment within the context of the parent node
var parserArgs = {context: parentNode.nodeName.toLowerCase(), data: data};
fragment = parser.parse(value, parserArgs);
markInlineFormatElements(fragment);
// Move the caret to a more suitable location
node = fragment.lastChild;
if (node.attr('id') == 'mce_marker') {
marker = node;
for (node = node.prev; node; node = node.walk(true)) {
if (node.type == 3 || !dom.isBlock(node.name)) {
if (editor.schema.isValidChild(node.parent.name, 'span')) {
node.parent.insert(marker, node, node.name === 'br');
}
break;
}
}
}
editor._selectionOverrides.showBlockCaretContainer(parentNode);
// If parser says valid we can insert the contents into that parent
if (!parserArgs.invalid) {
value = serializer.serialize(fragment);
// Check if parent is empty or only has one BR element then set the innerHTML of that parent
node = parentNode.firstChild;
node2 = parentNode.lastChild;
if (!node || (node === node2 && node.nodeName === 'BR')) {
dom.setHTML(parentNode, value);
} else {
selection.setContent(value);
}
} else {
// If the fragment was invalid within that context then we need
// to parse and process the parent it's inserted into
// Insert bookmark node and get the parent
selection.setContent(bookmarkHtml);
parentNode = selection.getNode();
rootNode = editor.getBody();
// Opera will return the document node when selection is in root
if (parentNode.nodeType == 9) {
parentNode = node = rootNode;
} else {
node = parentNode;
}
// Find the ancestor just before the root element
while (node !== rootNode) {
parentNode = node;
node = node.parentNode;
}
// Get the outer/inner HTML depending on if we are in the root and parser and serialize that
value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
value = serializer.serialize(
parser.parse(
// Need to replace by using a function since $ in the contents would otherwise be a problem
value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
return serializer.serialize(fragment);
})
)
);
// Set the inner/outer HTML depending on if we are in the root or not
if (parentNode == rootNode) {
dom.setHTML(rootNode, value);
} else {
dom.setOuterHTML(parentNode, value);
}
}
reduceInlineTextElements();
moveSelectionToMarker(dom.get('mce_marker'));
editor.fire('SetContent', args);
editor.addVisual();
},
mceInsertRawHTML: function(command, ui, value) {
selection.setContent('tiny_mce_marker');
editor.setContent(
editor.getContent().replace(/tiny_mce_marker/g, function() {
return value;
})
);
},
mceToggleFormat: function(command, ui, value) {
toggleFormat(value);
},
mceSetContent: function(command, ui, value) {
editor.setContent(value);
},
'Indent,Outdent': function(command) {
var intentValue, indentUnit, value;
// Setup indent level
intentValue = settings.indentation;
indentUnit = /[a-z%]+$/i.exec(intentValue);
intentValue = parseInt(intentValue, 10);
if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
// If forced_root_blocks is set to false we don't have a block to indent so lets create a div
if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) {
formatter.apply('div');
}
each(selection.getSelectedBlocks(), function(element) {
if (dom.getContentEditable(element) === "false") {
return;
}
if (element.nodeName != "LI") {
var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding';
indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left';
if (command == 'outdent') {
value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue);
dom.setStyle(element, indentStyleName, value ? value + indentUnit : '');
} else {
value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit;
dom.setStyle(element, indentStyleName, value);
}
}
});
} else {
execNativeCommand(command);
}
},
mceRepaint: function() {
},
InsertHorizontalRule: function() {
editor.execCommand('mceInsertContent', false, '<hr />');
},
mceToggleVisualAid: function() {
editor.hasVisual = !editor.hasVisual;
editor.addVisual();
},
mceReplaceContent: function(command, ui, value) {
editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'})));
},
mceInsertLink: function(command, ui, value) {
var anchor;
if (typeof value == 'string') {
value = {href: value};
}
anchor = dom.getParent(selection.getNode(), 'a');
// Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
value.href = value.href.replace(' ', '%20');
// Remove existing links if there could be child links or that the href isn't specified
if (!anchor || !value.href) {
formatter.remove('link');
}
// Apply new link to selection
if (value.href) {
formatter.apply('link', value, anchor);
}
},
selectAll: function() {
var root = dom.getRoot(), rng;
if (selection.getRng().setStart) {
rng = dom.createRng();
rng.setStart(root, 0);
rng.setEnd(root, root.childNodes.length);
selection.setRng(rng);
} else {
// IE will render it's own root level block elements and sometimes
// even put font elements in them when the user starts typing. So we need to
// move the selection to a more suitable element from this:
// <body>|<p></p></body> to this: <body><p>|</p></body>
rng = selection.getRng();
if (!rng.item) {
rng.moveToElementText(root);
rng.select();
}
}
},
"delete": function() {
execNativeCommand("Delete");
// Check if body is empty after the delete call if so then set the contents
// to an empty string and move the caret to any block produced by that operation
// this fixes the issue with root blocks not being properly produced after a delete call on IE
var body = editor.getBody();
if (dom.isEmpty(body)) {
editor.setContent('');
if (body.firstChild && dom.isBlock(body.firstChild)) {
editor.selection.setCursorLocation(body.firstChild, 0);
} else {
editor.selection.setCursorLocation(body, 0);
}
}
},
mceNewDocument: function() {
editor.setContent('');
},
InsertLineBreak: function(command, ui, value) {
// We load the current event in from EnterKey.js when appropriate to heed
// certain event-specific variations such as ctrl-enter in a list
var evt = value;
var brElm, extraBr, marker;
var rng = selection.getRng(true);
new RangeUtils(dom).normalize(rng);
var offset = rng.startOffset;
var container = rng.startContainer;
// Resolve node index
if (container.nodeType == 1 && container.hasChildNodes()) {
var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
if (isAfterLastNodeInContainer && container.nodeType == 3) {
offset = container.nodeValue.length;
} else {
offset = 0;
}
}
var parentBlock = dom.getParent(container, dom.isBlock);
var parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
// Enter inside block contained within a LI then split or insert before/after LI
var isControlKey = evt && evt.ctrlKey;
if (containerBlockName == 'LI' && !isControlKey) {
parentBlock = containerBlock;
parentBlockName = containerBlockName;
}
// Walks the parent block to the right and look for BR elements
function hasRightSideContent() {
var walker = new TreeWalker(container, parentBlock), node;
var nonEmptyElementsMap = editor.schema.getNonEmptyElements();
while ((node = walker.next())) {
if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
return true;
}
}
}
if (container && container.nodeType == 3 && offset >= container.nodeValue.length) {
// Insert extra BR element at the end block elements
if (!isOldIE && !hasRightSideContent()) {
brElm = dom.create('br');
rng.insertNode(brElm);
rng.setStartAfter(brElm);
rng.setEndAfter(brElm);
extraBr = true;
}
}
brElm = dom.create('br');
rng.insertNode(brElm);
// Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it
var documentMode = dom.doc.documentMode;
if (isOldIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) {
brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm);
}
// Insert temp marker and scroll to that
marker = dom.create('span', {}, ' ');
brElm.parentNode.insertBefore(marker, brElm);
selection.scrollIntoView(marker);
dom.remove(marker);
if (!extraBr) {
rng.setStartAfter(brElm);
rng.setEndAfter(brElm);
} else {
rng.setStartBefore(brElm);
rng.setEndBefore(brElm);
}
selection.setRng(rng);
editor.undoManager.add();
return TRUE;
}
});
// Add queryCommandState overrides
addCommands({
// Override justify commands
'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) {
var name = 'align' + command.substring(7);
var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks();
var matches = map(nodes, function(node) {
return !!formatter.matchNode(node, name);
});
return inArray(matches, TRUE) !== -1;
},
'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
return isFormatMatch(command);
},
mceBlockQuote: function() {
return isFormatMatch('blockquote');
},
Outdent: function() {
var node;
if (settings.inline_styles) {
if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
return TRUE;
}
if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
return TRUE;
}
}
return (
queryCommandState('InsertUnorderedList') ||
queryCommandState('InsertOrderedList') ||
(!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'))
);
},
'InsertUnorderedList,InsertOrderedList': function(command) {
var list = dom.getParent(selection.getNode(), 'ul,ol');
return list &&
(
command === 'insertunorderedlist' && list.tagName === 'UL' ||
command === 'insertorderedlist' && list.tagName === 'OL'
);
}
}, 'state');
// Add queryCommandValue overrides
addCommands({
'FontSize,FontName': function(command) {
var value = 0, parent;
if ((parent = dom.getParent(selection.getNode(), 'span'))) {
if (command == 'fontsize') {
value = parent.style.fontSize;
} else {
value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();
}
}
return value;
}
}, 'value');
// Add undo manager logic
addCommands({
Undo: function() {
editor.undoManager.undo();
},
Redo: function() {
editor.undoManager.redo();
}
});
};
});
| mit |
Subsets and Splits