<commit_before>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

/*
 * This file defines macros that declare and implement factories for
 * pluggable fMBT modules, such as adapters, heuristics and coverages.
 *
 * Every module registers its name with a creator function pointer to
 * <Module>Factory::creators. Registered modules are instantiated by
 * calling <Module>Factory::create(name, ...) that calls associated
 * creator function. Yet FACTORY_DEFAULT_CREATOR provides a default
 * creator function, modules that need to do something special in
 * creators can define their own functions and use
 * <Module>Factory::Register for registering it.
 *
 * FACTORY_DECLARATION(Module) is needed in the header file of the
 * Module base class only.
 *
 * FACTORY_IMPLEMENTATION(Module) is needed in the implementation of
 * the Module base class only.
 *
 * FACTORY_DEFAULT_CREATOR(Module, Class, Name) is needed in
 * the implementation of every Class that implements Module.
 */

#ifndef __factory_h__
#define __factory_h__

#include <vector>
#include <map>
#include <string>
#include <stdlib.h>

#ifndef FACTORY_CREATE_PARAMS
#define FACTORY_CREATE_PARAMS Log& log,                                \
                       std::string name,                               \
                       std::string params
#endif

#ifndef FACTORY_CREATE_DEFAULT_PARAMS
#define FACTORY_CREATE_DEFAULT_PARAMS = ""
#endif

#ifndef FACTORY_CREATOR_PARAMS
#define FACTORY_CREATOR_PARAMS Log& log, std::string params
#define FACTORY_CREATOR_PARAMS2 log, params
#endif

#undef FACTORY_DECLARATION
#undef FACTORY_IMPLEMENTATION
#undef FACTORY_DEFAULT_CREATOR

#define FACTORY_DECLARATION(MODULETYPE)                                \
                                                                       \
class MODULETYPE;                                                      \
                                                                       \
namespace MODULETYPE##Factory {                                        \
                                                                       \
    typedef MODULETYPE*(*creator)(FACTORY_CREATOR_PARAMS);             \
                                                                       \
    extern MODULETYPE* create(FACTORY_CREATE_PARAMS);                  \
                                                                       \
    extern void add_factory(std::string name, creator c);              \
                                                                       \
    extern std::map<std::string, creator>* creators;                   \
                                                                       \
    struct Register {                                                  \
        Register(std::string name, creator c) {                        \
            add_factory(name, c);                                      \
        }                                                              \
    };                                                                 \
}
#define FACTORY_ATEXIT(MODULETYPE)                                     \
void MODULETYPE##_ATEXITFUNC() {			               \
  if (MODULETYPE##Factory::creators) 				       \
    delete MODULETYPE##Factory::creators ;			       \
  MODULETYPE##Factory::creators = 0;                                   \
 }

#define FACTORY_CREATORS(MODULETYPE)                                   \
std::map<std::string, MODULETYPE##Factory::creator>*                   \
    MODULETYPE##Factory::creators = 0;

#define FACTORY_ADD_FACTORY(MODULETYPE)                                \
void MODULETYPE##Factory::add_factory(std::string name, creator c)     \
{                                                                      \
  if (!creators) {                                                     \
    creators = new std::map<std::string, MODULETYPE##Factory::creator>;\
    atexit(MODULETYPE##_ATEXITFUNC);                                   \
  }                                                                    \
  (*creators)[name] = c;                                               \
}

#define FACTORY_CREATE(MODULETYPE)                                     \
MODULETYPE* MODULETYPE##Factory::create(                               \
    FACTORY_CREATE_PARAMS FACTORY_CREATE_DEFAULT_PARAMS)               \
{                                                                      \
  if (!creators) return NULL;                                          \
                                                                       \
  creator c = (*creators)[name];                                       \
                                                                       \
  if (c) return c(FACTORY_CREATOR_PARAMS2);                            \
                                                                       \
  return NULL;                                                         \
}

#define FACTORY_IMPLEMENTATION(MODULETYPE)                             \
FACTORY_ATEXIT(MODULETYPE)                                             \
FACTORY_CREATORS(MODULETYPE)                                           \
FACTORY_ADD_FACTORY(MODULETYPE)                                        \
FACTORY_CREATE(MODULETYPE)

#define FACTORY_DEFAULT_CREATOR(MODULETYPE, CLASSNAME, ID)             \
namespace {                                                            \
  MODULETYPE* creator_func(FACTORY_CREATOR_PARAMS FACTORY_CREATE_DEFAULT_PARAMS)          \
  {                                                                    \
    return new CLASSNAME(FACTORY_CREATOR_PARAMS2);                     \
  }                                                                    \
  static MODULETYPE##Factory::Register me(ID, creator_func);           \
}

#endif
<commit_msg>Make it possible to use FACTORY_DEFAULT_CREATOR multiple times<commit_after>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

/*
 * This file defines macros that declare and implement factories for
 * pluggable fMBT modules, such as adapters, heuristics and coverages.
 *
 * Every module registers its name with a creator function pointer to
 * <Module>Factory::creators. Registered modules are instantiated by
 * calling <Module>Factory::create(name, ...) that calls associated
 * creator function. Yet FACTORY_DEFAULT_CREATOR provides a default
 * creator function, modules that need to do something special in
 * creators can define their own functions and use
 * <Module>Factory::Register for registering it.
 *
 * FACTORY_DECLARATION(Module) is needed in the header file of the
 * Module base class only.
 *
 * FACTORY_IMPLEMENTATION(Module) is needed in the implementation of
 * the Module base class only.
 *
 * FACTORY_DEFAULT_CREATOR(Module, Class, Name) is needed in
 * the implementation of every Class that implements Module.
 */

#ifndef __factory_h__
#define __factory_h__

#include <vector>
#include <map>
#include <string>
#include <stdlib.h>

#ifndef FACTORY_CREATE_PARAMS
#define FACTORY_CREATE_PARAMS Log& log,                                \
                       std::string name,                               \
                       std::string params
#endif

#ifndef FACTORY_CREATE_DEFAULT_PARAMS
#define FACTORY_CREATE_DEFAULT_PARAMS = ""
#endif

#ifndef FACTORY_CREATOR_PARAMS
#define FACTORY_CREATOR_PARAMS Log& log, std::string params
#define FACTORY_CREATOR_PARAMS2 log, params
#endif

#undef FACTORY_DECLARATION
#undef FACTORY_IMPLEMENTATION
#undef FACTORY_DEFAULT_CREATOR

#define FACTORY_DECLARATION(MODULETYPE)                                \
                                                                       \
class MODULETYPE;                                                      \
                                                                       \
namespace MODULETYPE##Factory {                                        \
                                                                       \
    typedef MODULETYPE*(*creator)(FACTORY_CREATOR_PARAMS);             \
                                                                       \
    extern MODULETYPE* create(FACTORY_CREATE_PARAMS);                  \
                                                                       \
    extern void add_factory(std::string name, creator c);              \
                                                                       \
    extern std::map<std::string, creator>* creators;                   \
                                                                       \
    struct Register {                                                  \
        Register(std::string name, creator c) {                        \
            add_factory(name, c);                                      \
        }                                                              \
    };                                                                 \
}
#define FACTORY_ATEXIT(MODULETYPE)                                     \
void MODULETYPE##_ATEXITFUNC() {			               \
  if (MODULETYPE##Factory::creators) 				       \
    delete MODULETYPE##Factory::creators ;			       \
  MODULETYPE##Factory::creators = 0;                                   \
 }

#define FACTORY_CREATORS(MODULETYPE)                                   \
std::map<std::string, MODULETYPE##Factory::creator>*                   \
    MODULETYPE##Factory::creators = 0;

#define FACTORY_ADD_FACTORY(MODULETYPE)                                \
void MODULETYPE##Factory::add_factory(std::string name, creator c)     \
{                                                                      \
  if (!creators) {                                                     \
    creators = new std::map<std::string, MODULETYPE##Factory::creator>;\
    atexit(MODULETYPE##_ATEXITFUNC);                                   \
  }                                                                    \
  (*creators)[name] = c;                                               \
}

#define FACTORY_CREATE(MODULETYPE)                                     \
MODULETYPE* MODULETYPE##Factory::create(                               \
    FACTORY_CREATE_PARAMS FACTORY_CREATE_DEFAULT_PARAMS)               \
{                                                                      \
  if (!creators) return NULL;                                          \
                                                                       \
  creator c = (*creators)[name];                                       \
                                                                       \
  if (c) return c(FACTORY_CREATOR_PARAMS2);                            \
                                                                       \
  return NULL;                                                         \
}

#define FACTORY_IMPLEMENTATION(MODULETYPE)                             \
FACTORY_ATEXIT(MODULETYPE)                                             \
FACTORY_CREATORS(MODULETYPE)                                           \
FACTORY_ADD_FACTORY(MODULETYPE)                                        \
FACTORY_CREATE(MODULETYPE)

#define CONCAT2(x, y)     x ## y
#define CONCAT(x, y)      CONCAT2(x, y)
#define UNIQUENAME(prefix) CONCAT(prefix, __LINE__)

#define FACTORY_DEFAULT_CREATOR(MODULETYPE, CLASSNAME, ID)	       \
namespace {                                                            \
  MODULETYPE* UNIQUENAME(creator_func) (FACTORY_CREATOR_PARAMS FACTORY_CREATE_DEFAULT_PARAMS) \
  {                                                                    \
    return new CLASSNAME(FACTORY_CREATOR_PARAMS2);                     \
  }                                                                    \
  static MODULETYPE##Factory::Register UNIQUENAME(me)(ID, UNIQUENAME(creator_func)); \
}

#endif

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
using boost::unit_test_framework::test_suite;

// BOOST
#include <boost/lexical_cast.hpp>

// STL
#include <functional>
#include <iostream>
#include <memory>

#include <iostream>

#include <mitkDataTreeNode.h>
#include <mitkStringProperty.h>
#include <mitkProperties.h>

using boost::unit_test_framework::test_suite;

void TestFunction()
{

  mitk::DataTreeNode::Pointer node;
  mitk::StringProperty::Pointer Prop;
  node = NULL;

  node = mitk::DataTreeNode::New();
  node->SetData(NULL);
  Prop = mitk::StringProperty::New("TestProp");
  node->SetProperty("stringPropTest",Prop);
  Prop = dynamic_cast<mitk::StringProperty *>(node->GetProperty("stringPropTest").GetPointer());
  BOOST_CHECK( Prop.IsNotNull() );
  BOOST_CHECK( Prop->GetValueAsString() == "TestProp");

  int intPropValue = 6;
  node->SetProperty("intProp", mitk::IntProperty::New(intPropValue) );
  mitk::IntProperty::Pointer intProp = dynamic_cast<mitk::IntProperty *>(node->GetProperty("intProp").GetPointer());
  BOOST_CHECK( intProp.IsNotNull() );
  BOOST_CHECK( intProp->GetValue() == intPropValue);

  node->SetProperty("boolProp", mitk::BoolProperty::New(true) );
  mitk::BoolProperty::Pointer boolProp = dynamic_cast<mitk::BoolProperty *>(node->GetProperty("boolProp").GetPointer());
  BOOST_CHECK(boolProp.IsNotNull() );
  BOOST_CHECK(boolProp->GetValue() == true);

  node->SetVisibility(false,NULL);
  BOOST_CHECK(node->IsVisible(NULL) == false );

  node->SetOpacity(0.0,NULL);
  float o;
  node->GetOpacity(o,NULL);
  BOOST_CHECK( o == 0.0 );

  node->SetOpacity(100.0,NULL);
  node->GetOpacity(o,NULL);
  BOOST_CHECK( o == 100.0 );

}

test_suite*
init_unit_test_suite( int argc, char * argv[] ) {

    test_suite* test= BOOST_TEST_SUITE( "Unit test example 1" );

    test->add( BOOST_TEST_CASE( &TestFunction ), 0 /* expected zero errors */ );

    return test;
}
<commit_msg>REM: deprecated test style removed<commit_after><|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
 ** Lexer for Lua language.
 **
 ** Written by Paul Winwood.
 ** Folder by Alexey Yutkin.
 ** Modified by Marcos E. Wurzius & Philippe Lhoste
 **/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
	return ch >= 0x80 ||
	       (isalnum(ch) || ch == '.' || ch == '_');
}

static inline bool IsAWordStart(int ch) {
	return ch >= 0x80 ||
	       (isalpha(ch) || ch == '_');
}

static inline bool IsANumberChar(int ch) {
	// Not exactly following number definition (several dots are seen as OK, etc.)
	// but probably enough in most cases.
	return (ch < 0x80) &&
	        (isdigit(ch) || toupper(ch) == 'E' ||
	        ch == '.' || ch == '-' || ch == '+' ||
	        (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}

static inline bool IsLuaOperator(int ch) {
	if (ch >= 0x80 || isalnum(ch)) {
		return false;
	}
	// '.' left out as it is used to make up numbers
	if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
		ch == '(' || ch == ')' || ch == '=' ||
		ch == '{' || ch == '}' || ch == '~' ||
		ch == '[' || ch == ']' || ch == ';' ||
		ch == '<' || ch == '>' || ch == ',' ||
		ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
		ch == '#') {
		return true;
	}
	return false;
}

// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
	int sep = 1;
	while (sc.GetRelative(sep) == '=' && sep < 0xFF)
		sep++;
	if (sc.GetRelative(sep) == sc.ch)
		return sep;
	return 0;
}

static void ColouriseLuaDoc(
	unsigned int startPos,
	int length,
	int initStyle,
	WordList *keywordlists[],
	Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];
	WordList &keywords3 = *keywordlists[2];
	WordList &keywords4 = *keywordlists[3];
	WordList &keywords5 = *keywordlists[4];
	WordList &keywords6 = *keywordlists[5];
	WordList &keywords7 = *keywordlists[6];
	WordList &keywords8 = *keywordlists[7];

	int currentLine = styler.GetLine(startPos);
	// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
	// if we are inside such a string. Block comment was introduced in Lua 5.0,
	// blocks with separators [=[ ... ]=] in Lua 5.1.
	int nestLevel = 0;
	int sepCount = 0;
	if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
		int lineState = styler.GetLineState(currentLine - 1);
		nestLevel = lineState >> 8;
		sepCount = lineState & 0xFF;
	}

	// Do not leak onto next line
	if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
		initStyle = SCE_LUA_DEFAULT;
	}

	StyleContext sc(startPos, length, initStyle, styler);
	if (startPos == 0 && sc.ch == '#') {
		// shbang line: # is a comment only if first char of the script
		sc.SetState(SCE_LUA_COMMENTLINE);
	}
	for (; sc.More(); sc.Forward()) {
		if (sc.atLineEnd) {
			// Update the line state, so it can be seen by next line
			currentLine = styler.GetLine(sc.currentPos);
			switch (sc.state) {
			case SCE_LUA_LITERALSTRING:
			case SCE_LUA_COMMENT:
				// Inside a literal string or block comment, we set the line state
				styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
				break;
			default:
				// Reset the line state
				styler.SetLineState(currentLine, 0);
				break;
			}
		}
		if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
			// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
			sc.SetState(SCE_LUA_STRING);
		}

		// Handle string line continuation
		if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
		        sc.ch == '\\') {
			if (sc.chNext == '\n' || sc.chNext == '\r') {
				sc.Forward();
				if (sc.ch == '\r' && sc.chNext == '\n') {
					sc.Forward();
				}
				continue;
			}
		}

		// Determine if the current state should terminate.
		if (sc.state == SCE_LUA_OPERATOR) {
			sc.SetState(SCE_LUA_DEFAULT);
		} else if (sc.state == SCE_LUA_NUMBER) {
			// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
			if (!IsANumberChar(sc.ch)) {
				sc.SetState(SCE_LUA_DEFAULT);
			} else if (sc.ch == '-' || sc.ch == '+') {
                                if (sc.chPrev != 'E' && sc.chPrev != 'e')
                                        sc.SetState(SCE_LUA_DEFAULT);
                        }
		} else if (sc.state == SCE_LUA_IDENTIFIER) {
			if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
				char s[100];
				sc.GetCurrent(s, sizeof(s));
				if (keywords.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD);
				} else if (keywords2.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD2);
				} else if (keywords3.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD3);
				} else if (keywords4.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD4);
				} else if (keywords5.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD5);
				} else if (keywords6.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD6);
				} else if (keywords7.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD7);
				} else if (keywords8.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD8);
				}
				sc.SetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
			if (sc.atLineEnd) {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_STRING) {
			if (sc.ch == '\\') {
				if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
					sc.Forward();
				}
			} else if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			} else if (sc.atLineEnd) {
				sc.ChangeState(SCE_LUA_STRINGEOL);
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_CHARACTER) {
			if (sc.ch == '\\') {
				if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
					sc.Forward();
				}
			} else if (sc.ch == '\'') {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			} else if (sc.atLineEnd) {
				sc.ChangeState(SCE_LUA_STRINGEOL);
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
			if (sc.ch == '[') {
				int sep = LongDelimCheck(sc);
				if (sep == 1 && sepCount == 1) {    // [[-only allowed to nest
					nestLevel++;
					sc.Forward();
				}
			} else if (sc.ch == ']') {
				int sep = LongDelimCheck(sc);
				if (sep == 1 && sepCount == 1) {    // un-nest with ]]-only
					nestLevel--;
					sc.Forward();
					if (nestLevel == 0) {
						sc.ForwardSetState(SCE_LUA_DEFAULT);
					}
				} else if (sep > 1 && sep == sepCount) {   // ]=]-style delim
					sc.Forward(sep);
					sc.ForwardSetState(SCE_LUA_DEFAULT);
				}
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_LUA_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_LUA_NUMBER);
				if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
					sc.Forward(1);
				}
			} else if (IsAWordStart(sc.ch)) {
				sc.SetState(SCE_LUA_IDENTIFIER);
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_LUA_STRING);
			} else if (sc.ch == '\'') {
				sc.SetState(SCE_LUA_CHARACTER);
			} else if (sc.ch == '[') {
				sepCount = LongDelimCheck(sc);
				if (sepCount == 0) {
					sc.SetState(SCE_LUA_OPERATOR);
				} else {
					nestLevel = 1;
					sc.SetState(SCE_LUA_LITERALSTRING);
					sc.Forward(sepCount);
				}
			} else if (sc.Match('-', '-')) {
				sc.SetState(SCE_LUA_COMMENTLINE);
				if (sc.Match("--[")) {
					sc.Forward(2);
					sepCount = LongDelimCheck(sc);
					if (sepCount > 0) {
						nestLevel = 1;
						sc.ChangeState(SCE_LUA_COMMENT);
						sc.Forward(sepCount);
					}
				} else {
					sc.Forward();
				}
			} else if (sc.atLineStart && sc.Match('$')) {
				sc.SetState(SCE_LUA_PREPROCESSOR);	// Obsolete since Lua 4.0, but still in old code
			} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
				sc.SetState(SCE_LUA_OPERATOR);
			}
		}
	}
	sc.Complete();
}

static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
                       Accessor &styler) {
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	int styleNext = styler.StyleAt(startPos);
	char s[10];

	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (style == SCE_LUA_WORD) {
			if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
				for (unsigned int j = 0; j < 8; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
				}

				if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
					levelCurrent++;
				}
				if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
					levelCurrent--;
				}
			}
		} else if (style == SCE_LUA_OPERATOR) {
			if (ch == '{' || ch == '(') {
				levelCurrent++;
			} else if (ch == '}' || ch == ')') {
				levelCurrent--;
			}
		} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
			if (ch == '[') {
				levelCurrent++;
			} else if (ch == ']') {
				levelCurrent--;
			}
		}

		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact) {
				lev |= SC_FOLDLEVELWHITEFLAG;
			}
			if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
				lev |= SC_FOLDLEVELHEADERFLAG;
			}
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch)) {
			visibleChars++;
		}
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later

	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const luaWordListDesc[] = {
	"Keywords",
	"Basic functions",
	"String, (table) & math functions",
	"(coroutines), I/O & system facilities",
	"user1",
	"user2",
	"user3",
	"user4",
	0
};

LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Kein-Hong Man to use CharacterSet objects. Simpler and smaller but should not change behaviour.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
 ** Lexer for Lua language.
 **
 ** Written by Paul Winwood.
 ** Folder by Alexey Yutkin.
 ** Modified by Marcos E. Wurzius & Philippe Lhoste
 **/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "CharacterSet.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
	int sep = 1;
	while (sc.GetRelative(sep) == '=' && sep < 0xFF)
		sep++;
	if (sc.GetRelative(sep) == sc.ch)
		return sep;
	return 0;
}

static void ColouriseLuaDoc(
	unsigned int startPos,
	int length,
	int initStyle,
	WordList *keywordlists[],
	Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];
	WordList &keywords3 = *keywordlists[2];
	WordList &keywords4 = *keywordlists[3];
	WordList &keywords5 = *keywordlists[4];
	WordList &keywords6 = *keywordlists[5];
	WordList &keywords7 = *keywordlists[6];
	WordList &keywords8 = *keywordlists[7];

	// Accepts accented characters
	CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
	CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
	// Not exactly following number definition (several dots are seen as OK, etc.)
	// but probably enough in most cases.
	CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefABCDEF");
	CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#");
	CharacterSet setEscapeSkip(CharacterSet::setNone, "\"'\\");

	int currentLine = styler.GetLine(startPos);
	// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
	// if we are inside such a string. Block comment was introduced in Lua 5.0,
	// blocks with separators [=[ ... ]=] in Lua 5.1.
	int nestLevel = 0;
	int sepCount = 0;
	if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
		int lineState = styler.GetLineState(currentLine - 1);
		nestLevel = lineState >> 8;
		sepCount = lineState & 0xFF;
	}

	// Do not leak onto next line
	if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
		initStyle = SCE_LUA_DEFAULT;
	}

	StyleContext sc(startPos, length, initStyle, styler);
	if (startPos == 0 && sc.ch == '#') {
		// shbang line: # is a comment only if first char of the script
		sc.SetState(SCE_LUA_COMMENTLINE);
	}
	for (; sc.More(); sc.Forward()) {
		if (sc.atLineEnd) {
			// Update the line state, so it can be seen by next line
			currentLine = styler.GetLine(sc.currentPos);
			switch (sc.state) {
			case SCE_LUA_LITERALSTRING:
			case SCE_LUA_COMMENT:
				// Inside a literal string or block comment, we set the line state
				styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
				break;
			default:
				// Reset the line state
				styler.SetLineState(currentLine, 0);
				break;
			}
		}
		if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
			// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
			sc.SetState(SCE_LUA_STRING);
		}

		// Handle string line continuation
		if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
				sc.ch == '\\') {
			if (sc.chNext == '\n' || sc.chNext == '\r') {
				sc.Forward();
				if (sc.ch == '\r' && sc.chNext == '\n') {
					sc.Forward();
				}
				continue;
			}
		}

		// Determine if the current state should terminate.
		if (sc.state == SCE_LUA_OPERATOR) {
			sc.SetState(SCE_LUA_DEFAULT);
		} else if (sc.state == SCE_LUA_NUMBER) {
			// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
			if (!setNumber.Contains(sc.ch)) {
				sc.SetState(SCE_LUA_DEFAULT);
			} else if (sc.ch == '-' || sc.ch == '+') {
				if (sc.chPrev != 'E' && sc.chPrev != 'e')
					sc.SetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_IDENTIFIER) {
			if (!setWord.Contains(sc.ch) || sc.Match('.', '.')) {
				char s[100];
				sc.GetCurrent(s, sizeof(s));
				if (keywords.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD);
				} else if (keywords2.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD2);
				} else if (keywords3.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD3);
				} else if (keywords4.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD4);
				} else if (keywords5.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD5);
				} else if (keywords6.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD6);
				} else if (keywords7.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD7);
				} else if (keywords8.InList(s)) {
					sc.ChangeState(SCE_LUA_WORD8);
				}
				sc.SetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
			if (sc.atLineEnd) {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_STRING) {
			if (sc.ch == '\\') {
				if (setEscapeSkip.Contains(sc.chNext)) {
					sc.Forward();
				}
			} else if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			} else if (sc.atLineEnd) {
				sc.ChangeState(SCE_LUA_STRINGEOL);
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_CHARACTER) {
			if (sc.ch == '\\') {
				if (setEscapeSkip.Contains(sc.chNext)) {
					sc.Forward();
				}
			} else if (sc.ch == '\'') {
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			} else if (sc.atLineEnd) {
				sc.ChangeState(SCE_LUA_STRINGEOL);
				sc.ForwardSetState(SCE_LUA_DEFAULT);
			}
		} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
			if (sc.ch == '[') {
				int sep = LongDelimCheck(sc);
				if (sep == 1 && sepCount == 1) {    // [[-only allowed to nest
					nestLevel++;
					sc.Forward();
				}
			} else if (sc.ch == ']') {
				int sep = LongDelimCheck(sc);
				if (sep == 1 && sepCount == 1) {    // un-nest with ]]-only
					nestLevel--;
					sc.Forward();
					if (nestLevel == 0) {
						sc.ForwardSetState(SCE_LUA_DEFAULT);
					}
				} else if (sep > 1 && sep == sepCount) {   // ]=]-style delim
					sc.Forward(sep);
					sc.ForwardSetState(SCE_LUA_DEFAULT);
				}
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_LUA_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_LUA_NUMBER);
				if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
					sc.Forward();
				}
			} else if (setWordStart.Contains(sc.ch)) {
				sc.SetState(SCE_LUA_IDENTIFIER);
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_LUA_STRING);
			} else if (sc.ch == '\'') {
				sc.SetState(SCE_LUA_CHARACTER);
			} else if (sc.ch == '[') {
				sepCount = LongDelimCheck(sc);
				if (sepCount == 0) {
					sc.SetState(SCE_LUA_OPERATOR);
				} else {
					nestLevel = 1;
					sc.SetState(SCE_LUA_LITERALSTRING);
					sc.Forward(sepCount);
				}
			} else if (sc.Match('-', '-')) {
				sc.SetState(SCE_LUA_COMMENTLINE);
				if (sc.Match("--[")) {
					sc.Forward(2);
					sepCount = LongDelimCheck(sc);
					if (sepCount > 0) {
						nestLevel = 1;
						sc.ChangeState(SCE_LUA_COMMENT);
						sc.Forward(sepCount);
					}
				} else {
					sc.Forward();
				}
			} else if (sc.atLineStart && sc.Match('$')) {
				sc.SetState(SCE_LUA_PREPROCESSOR);	// Obsolete since Lua 4.0, but still in old code
			} else if (setLuaOperator.Contains(sc.ch)) {
				sc.SetState(SCE_LUA_OPERATOR);
			}
		}
	}
	sc.Complete();
}

static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
                       Accessor &styler) {
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	int styleNext = styler.StyleAt(startPos);
	char s[10];

	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (style == SCE_LUA_WORD) {
			if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
				for (unsigned int j = 0; j < 8; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
				}

				if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
					levelCurrent++;
				}
				if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
					levelCurrent--;
				}
			}
		} else if (style == SCE_LUA_OPERATOR) {
			if (ch == '{' || ch == '(') {
				levelCurrent++;
			} else if (ch == '}' || ch == ')') {
				levelCurrent--;
			}
		} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
			if (ch == '[') {
				levelCurrent++;
			} else if (ch == ']') {
				levelCurrent--;
			}
		}

		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact) {
				lev |= SC_FOLDLEVELWHITEFLAG;
			}
			if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
				lev |= SC_FOLDLEVELHEADERFLAG;
			}
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch)) {
			visibleChars++;
		}
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later

	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const luaWordListDesc[] = {
	"Keywords",
	"Basic functions",
	"String, (table) & math functions",
	"(coroutines), I/O & system facilities",
	"user1",
	"user2",
	"user3",
	"user4",
	0
};

LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/optimize/operator_property.h"

namespace tflite {
namespace optimize {
namespace operator_property {
TfLiteStatus GetOperatorProperty(const BuiltinOperator& op,
                                 OperatorProperty* property) {
  if (op == BuiltinOperator_ADD || op == BuiltinOperator_MUL) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_AVERAGE_POOL_2D ||
      op == BuiltinOperator_MAX_POOL_2D || op == BuiltinOperator_SQUEEZE) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = true;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_CONCATENATION) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = true;
    property->input_indexes = {};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = true;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_CONV_2D) {
    property->per_axis = true;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_DEPTHWISE_CONV_2D) {
    property->per_axis = true;
    property->per_axis_index = 3;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_FULLY_CONNECTED) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_MEAN || op == BuiltinOperator_PAD ||
      op == BuiltinOperator_QUANTIZE || op == BuiltinOperator_RESHAPE) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_SOFTMAX) {
    // Softmax requires output with 1/256 as scale and -128 as zero point.
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = true;
    property->restricted_value_on_output = {1 / 256.0, -128};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_TANH) {
    // Tanh requires output with 1/128 as scale and 0 as zero point.
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = true;
    property->restricted_value_on_output = {1 / 128.0, 0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_ARG_MAX) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    // ArgMax has no quantizable output, so there is nothing to do here.
    property->output_indexes = {};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {};
    return kTfLiteOk;
  }
  return kTfLiteError;
}

}  // namespace operator_property
}  // namespace optimize
}  // namespace tflite
<commit_msg>Fix gcc6.3 compilation failure.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/optimize/operator_property.h"

namespace tflite {
namespace optimize {
namespace operator_property {
TfLiteStatus GetOperatorProperty(const BuiltinOperator& op,
                                 OperatorProperty* property) {
  if (op == BuiltinOperator_ADD || op == BuiltinOperator_MUL) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output =  {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_AVERAGE_POOL_2D ||
      op == BuiltinOperator_MAX_POOL_2D || op == BuiltinOperator_SQUEEZE) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = true;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_CONCATENATION) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = true;
    property->input_indexes = {};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = true;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_CONV_2D) {
    property->per_axis = true;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_DEPTHWISE_CONV_2D) {
    property->per_axis = true;
    property->per_axis_index = 3;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_FULLY_CONNECTED) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0, 1};
    property->output_indexes = {0};
    property->biases = {2};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_MEAN || op == BuiltinOperator_PAD ||
      op == BuiltinOperator_QUANTIZE || op == BuiltinOperator_RESHAPE) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_SOFTMAX) {
    // Softmax requires output with 1/256 as scale and -128 as zero point.
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = true;
    property->restricted_value_on_output = {1 / 256.0, -128};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_TANH) {
    // Tanh requires output with 1/128 as scale and 0 as zero point.
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    property->output_indexes = {0};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = true;
    property->restricted_value_on_output = {1 / 128.0, 0};
    return kTfLiteOk;
  }
  if (op == BuiltinOperator_ARG_MAX) {
    property->per_axis = false;
    property->per_axis_index = 0;
    property->arbitrary_inputs = false;
    property->input_indexes = {0};
    // ArgMax has no quantizable output, so there is nothing to do here.
    property->output_indexes = {};
    property->biases = {};
    property->restrict_same_input_output_scale = false;
    property->restriction_on_output = false;
    property->restricted_value_on_output = {0.0,0.0};
    return kTfLiteOk;
  }
  return kTfLiteError;
}

}  // namespace operator_property
}  // namespace optimize
}  // namespace tflite
<|endoftext|>


<commit_before>// WindowsService.cpp : Entry point for the service
//

#include "stdafx.h"
#include "ServiceInstaller.h"
#include "ServiceBase.h"
#include "WindowsServiceImpl.h"

// Internal name of the service
#define SERVICE_NAME             L"Redis"

// Displayed name of the service
#define SERVICE_DISPLAY_NAME     L"Redis Service"

// Displayed service description
#define SERVICE_DISPLAY_DESCRIPTION	L"Hosts Redis server in a windows service"

// Service start options.
#define SERVICE_START_TYPE       SERVICE_AUTO_START

// List of service dependencies - "dep1\0dep2\0\0"
#define SERVICE_DEPENDENCIES     L""

// The name of the account under which the service should run
#define SERVICE_ACCOUNT          L"NT AUTHORITY\\LocalService"

// The password to the service account name
#define SERVICE_PASSWORD         NULL

CWindowsServiceImpl* service = NULL;

BOOL ctrlHandler(DWORD fdwCtrlType)
{
	BOOL result = S_OK;

	switch (fdwCtrlType)
	{
		// Handle the CTRL-C signal.
		case CTRL_C_EVENT:
			printf("Ctrl-C pressed, exiting...\n\n");
			break;
		// CTRL-CLOSE: confirm that the user wants to exit.
		case CTRL_CLOSE_EVENT:
			printf("Window is closing...\n\n");
			break;
		// Pass other signals to the next handler.
		case CTRL_BREAK_EVENT:
			printf("Ctrl-Break pressed, exiting...\n\n");
			break;
		case CTRL_LOGOFF_EVENT:
			printf("Logoff detected, exiting...\n\n");
			break;
		case CTRL_SHUTDOWN_EVENT:
			printf("System shutdown, exiting...\n\n");
			break;
		default:
			result = S_FALSE;
			break;
	}

	if (result == S_OK)
		shutdown();

	printf("Exit done");

	return result;
}

int wmain(int argc, wchar_t *argv[])
{
	// Executed as console application
    if ((argc > 1) && ((*argv[1] == L'-' || (*argv[1] == L'/'))))
    {
        if (_wcsicmp(L"install", argv[1] + 1) == 0)
        {
            // Install the service when the command is
            // "-install" or "/install".

            InstallService(
                SERVICE_NAME,                // Name of service
                SERVICE_DISPLAY_NAME,        // Name to display
				SERVICE_DISPLAY_DESCRIPTION, // Description to display
                SERVICE_START_TYPE,          // Service start type
                SERVICE_DEPENDENCIES,        // Dependencies
                SERVICE_ACCOUNT,             // Service running account
                SERVICE_PASSWORD             // Password of the account
                );
        }
        else if (_wcsicmp(L"remove", argv[1] + 1) == 0)
        {
            // Uninstall the service when the command is
            // "-remove" or "/remove".
            UninstallService(SERVICE_NAME);
        }
		else if (_wcsicmp(L"commandline", argv[1] + 1) == 0)
		{
			// Set keyboard event handler
			SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlHandler, TRUE);

			// Execute functionality as command line console tool
			service = new CWindowsServiceImpl(SERVICE_NAME);

			if (service)
				service->ServiceWorkerThread();
		}
    }
    else
    {
        wprintf(L"Parameters:\n");
        wprintf(L" /install      to install the service.\n");
        wprintf(L" /remove       to remove the service.\n");
		wprintf(L" /commandline  to execute as CLI tool.\n");
    }

	// Executed as a service from SCM
	if (argc <= 1)
	{
		service = new CWindowsServiceImpl(SERVICE_NAME);
		CServiceBase::Run(*service);
	}

    return 0;
}

void shutdown()
{
	if (service)
	{
		service->OnStop();

		delete service;
		service = NULL;
	}
}<commit_msg>Fixed check for executed as a service<commit_after>// WindowsService.cpp : Entry point for the service
//

#include "stdafx.h"
#include "ServiceInstaller.h"
#include "ServiceBase.h"
#include "WindowsServiceImpl.h"
#include <process.h>

bool isrunningasservice(unsigned int pid);

// Internal name of the service
#define SERVICE_NAME             L"Redis"

// Displayed name of the service
#define SERVICE_DISPLAY_NAME     L"Redis Service"

// Displayed service description
#define SERVICE_DISPLAY_DESCRIPTION	L"Hosts Redis server in a windows service"

// Service start options.
#define SERVICE_START_TYPE       SERVICE_AUTO_START

// List of service dependencies - "dep1\0dep2\0\0"
#define SERVICE_DEPENDENCIES     L""

// The name of the account under which the service should run
#define SERVICE_ACCOUNT          L"NT AUTHORITY\\LocalService"

// The password to the service account name
#define SERVICE_PASSWORD         NULL

CWindowsServiceImpl* service = NULL;

BOOL ctrlHandler(DWORD fdwCtrlType)
{
	BOOL result = S_OK;

	switch (fdwCtrlType)
	{
		// Handle the CTRL-C signal.
		case CTRL_C_EVENT:
			printf("Ctrl-C pressed, exiting...\n\n");
			break;
		// CTRL-CLOSE: confirm that the user wants to exit.
		case CTRL_CLOSE_EVENT:
			printf("Window is closing...\n\n");
			break;
		// Pass other signals to the next handler.
		case CTRL_BREAK_EVENT:
			printf("Ctrl-Break pressed, exiting...\n\n");
			break;
		case CTRL_LOGOFF_EVENT:
			printf("Logoff detected, exiting...\n\n");
			break;
		case CTRL_SHUTDOWN_EVENT:
			printf("System shutdown, exiting...\n\n");
			break;
		default:
			result = S_FALSE;
			break;
	}

	if (result == S_OK)
		shutdown();

	printf("Exit done");

	return result;
}

int wmain(int argc, wchar_t *argv[])
{
	// Executed as console application
    if ((argc > 1) && ((*argv[1] == L'-' || (*argv[1] == L'/'))))
    {
        if (_wcsicmp(L"install", argv[1] + 1) == 0)
        {
            // Install the service when the command is
            // "-install" or "/install".

            InstallService(
                SERVICE_NAME,                // Name of service
                SERVICE_DISPLAY_NAME,        // Name to display
				SERVICE_DISPLAY_DESCRIPTION, // Description to display
                SERVICE_START_TYPE,          // Service start type
                SERVICE_DEPENDENCIES,        // Dependencies
                SERVICE_ACCOUNT,             // Service running account
                SERVICE_PASSWORD             // Password of the account
                );
        }
        else if (_wcsicmp(L"remove", argv[1] + 1) == 0)
        {
            // Uninstall the service when the command is
            // "-remove" or "/remove".
            UninstallService(SERVICE_NAME);
        }
		else if (_wcsicmp(L"commandline", argv[1] + 1) == 0)
		{
			// Set keyboard event handler
			SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlHandler, TRUE);

			// Execute functionality as command line console tool
			service = new CWindowsServiceImpl(SERVICE_NAME);

			if (service)
				service->ServiceWorkerThread();
		}
    }
    else if (isrunningasservice(_getpid()))
	{
		// Start service instance when executed as a service from SCM
		service = new CWindowsServiceImpl(SERVICE_NAME);
		CServiceBase::Run(*service);
	}
	else
    {
        wprintf(L"Parameters:\n");
        wprintf(L" /install      to install the service.\n");
        wprintf(L" /remove       to remove the service.\n");
		wprintf(L" /commandline  to execute as CLI tool.\n");
    }

    return 0;
}

void shutdown()
{
	if (service)
	{
		service->OnStop();

		delete service;
		service = NULL;
	}
}

bool isrunningasservice(unsigned int pid)
{
    bool result = false;

	try
	{
		SC_HANDLE hScm = OpenSCManager(
			0,
			SERVICES_ACTIVE_DATABASE,
			SC_MANAGER_ENUMERATE_SERVICE
		);

		if (hScm == 0)
			return result;

		DWORD ServicesBufferRequired = 0;
		DWORD ResumeHandle = 0;

		DWORD ServicesBufferSize = 0;
		DWORD ServicesCount = 0;
		ENUM_SERVICE_STATUS_PROCESS* ServicesBuffer = 0;

		EnumServicesStatusEx(hScm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
		SERVICE_ACTIVE, 0, 0, &ServicesBufferRequired, &ServicesCount, &ResumeHandle, 0);

		ServicesBuffer = (ENUM_SERVICE_STATUS_PROCESS*)new char[ServicesBufferRequired];
		ServicesBufferSize = ServicesBufferRequired;
		EnumServicesStatusEx(hScm,
							SC_ENUM_PROCESS_INFO,
							SERVICE_WIN32,
							SERVICE_ACTIVE,
							(LPBYTE)ServicesBuffer,
							ServicesBufferSize,
							&ServicesBufferRequired,
							&ServicesCount,
							&ResumeHandle,
							0);

		ENUM_SERVICE_STATUS_PROCESS* ServicesBufferPtr = ServicesBuffer;
		while (ServicesCount--)
		{
			if (ServicesBufferPtr->ServiceStatusProcess.dwProcessId == pid)
			{
				result = true;
				break;
			}

			ServicesBufferPtr++;
		}

		delete [] ServicesBuffer;

		CloseServiceHandle(hScm);
	}
	catch(...)
	{
	}

    return result;
}<|endoftext|>


<commit_before>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Eigen>

#include <sstream>

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    NanScope();

    if (args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      element_type value = args[2]->NumberValue();

      Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
          ctr->NewInstance(
              sizeof(argv)/sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row >= matrix.rows() || col >= matrix.cols() ?
        NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_MATRIX_HPP
<commit_msg>src: fixed 'is_out_of_range()' in Matrix.hpp<commit_after>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Eigen>

#include <sstream>

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    NanScope();

    if (args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      element_type value = args[2]->NumberValue();

      Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();
      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();
      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
          ctr->NewInstance(
              sizeof(argv)/sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_MATRIX_HPP
<|endoftext|>


<commit_before>#include "Memory.h"

#include "imguiext/imguial_fonts.h"

#include <stdint.h>

bool Memory::init(libretro::Core* core, Platform platform)
{
  _core = core;
  _platform = platform;
  _opened = true;

  switch (platform)
  {
  case Platform::kNES:  return initNES();
  case Platform::kSNES: return initSNES();
  case Platform::kSMS:  return initSMS();
  default:              return false;
  }
}

void Memory::destroy()
{
  _regions.clear();
}

void Memory::draw()
{
  for (auto it = _regions.begin(); it != _regions.end(); ++it)
  {
    Region* region = &*it;

    region->_editor.Draw(region->_description.c_str(), (unsigned char*)region->_contents, region->_size, region->_baseAddr);
  }
}

bool Memory::initWidthMmap(const Block* block)
{
  const struct retro_memory_map* mmap = _core->getMemoryMap();

  if (mmap == NULL || mmap->num_descriptors == 0)
  {
    return false;
  }

  for (int i = 0; block->_name != NULL; i++, block++)
  {
    const struct retro_memory_descriptor* desc = mmap->descriptors;
    bool found = false;

    for (unsigned j = 0; j < mmap->num_descriptors; j++, desc++)
    {
      if (desc->start == block->_start)
      {
        found = true;
        break;
      }
    }

    if (!found)
    {
      _regions.clear();
      return false;
    }

    Region region;

    region._description = ICON_FA_MICROCHIP;
    region._description.append(" ");
    region._description.append(block->_name);

    region._contents = desc->ptr;
    region._size     = desc->len;
    region._baseAddr = desc->start;

    region._editor.Open = false;

    _regions.push_back(region);
  }

  return true;
}

bool Memory::initWidthMdata(const Block* block)
{
  for (int i = 0; block->_name != NULL; i++, block++)
  {
    void* contents = _core->getMemoryData(block->_id);

    if (contents == NULL)
    {
      _regions.clear();
      return false;
    }

    Region region;

    region._description = ICON_FA_MICROCHIP;
    region._description.append(" ");
    region._description.append(block->_name);

    region._contents = contents;
    region._size     = _core->getMemorySize(block->_id);
    region._baseAddr = block->_start;

    region._editor.Open = false;

    _regions.push_back(region);
  }

  return true;
}

bool Memory::initNES()
{
  static const Block blocks[] =
  {
    {RETRO_MEMORY_SYSTEM_RAM, 0x0000, "Work RAM"},
    {RETRO_MEMORY_SAVE_RAM,   0x6000, "Save RAM"},
    {0,                       0x0000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  return ok;
}

bool Memory::initSNES()
{
  static const Block blocks[] =
  {
    {RETRO_MEMORY_SYSTEM_RAM, 0x000000, "Work RAM"},
    {RETRO_MEMORY_SAVE_RAM,   0x700000, "Save RAM"},
    {0,                       0x000000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  return ok;
}

bool Memory::initSMS()
{
  static const Block blocks[] =
  {
    //{RETRO_MEMORY_SYSTEM_RAM, 0xc000, "Work RAM"},
    {RETRO_MEMORY_SYSTEM_RAM, 0x0000, "Work RAM"},
    {0,                       0x000000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  for (auto it = _regions.begin(); it != _regions.end(); ++it)
  {
    if (it->_baseAddr == 0xc000)
    {
      // Remove mirror from system RAM
      //it->_size = 8192;
      break;
    }
  }

  return ok;
}
<commit_msg>Fixed Sega Master System memory watch<commit_after>#include "Memory.h"

#include "imguiext/imguial_fonts.h"

#include <stdint.h>

bool Memory::init(libretro::Core* core, Platform platform)
{
  _core = core;
  _platform = platform;
  _opened = true;

  switch (platform)
  {
  case Platform::kNES:  return initNES();
  case Platform::kSNES: return initSNES();
  case Platform::kSMS:  return initSMS();
  default:              return false;
  }
}

void Memory::destroy()
{
  _regions.clear();
}

void Memory::draw()
{
  for (auto it = _regions.begin(); it != _regions.end(); ++it)
  {
    Region* region = &*it;

    region->_editor.Draw(region->_description.c_str(), (unsigned char*)region->_contents, region->_size, region->_baseAddr);
  }
}

bool Memory::initWidthMmap(const Block* block)
{
  const struct retro_memory_map* mmap = _core->getMemoryMap();

  if (mmap == NULL || mmap->num_descriptors == 0)
  {
    return false;
  }

  for (int i = 0; block->_name != NULL; i++, block++)
  {
    const struct retro_memory_descriptor* desc = mmap->descriptors;
    bool found = false;

    for (unsigned j = 0; j < mmap->num_descriptors; j++, desc++)
    {
      if (desc->start == block->_start)
      {
        found = true;
        break;
      }
    }

    if (!found)
    {
      _regions.clear();
      return false;
    }

    Region region;

    region._description = ICON_FA_MICROCHIP;
    region._description.append(" ");
    region._description.append(block->_name);

    region._contents = desc->ptr;
    region._size     = desc->len;
    region._baseAddr = desc->start;

    region._editor.Open = false;

    _regions.push_back(region);
  }

  return true;
}

bool Memory::initWidthMdata(const Block* block)
{
  for (int i = 0; block->_name != NULL; i++, block++)
  {
    void* contents = _core->getMemoryData(block->_id);

    if (contents == NULL)
    {
      _regions.clear();
      return false;
    }

    Region region;

    region._description = ICON_FA_MICROCHIP;
    region._description.append(" ");
    region._description.append(block->_name);

    region._contents = contents;
    region._size     = _core->getMemorySize(block->_id);
    region._baseAddr = block->_start;

    region._editor.Open = false;

    _regions.push_back(region);
  }

  return true;
}

bool Memory::initNES()
{
  static const Block blocks[] =
  {
    {RETRO_MEMORY_SYSTEM_RAM, 0x0000, "Work RAM"},
    {RETRO_MEMORY_SAVE_RAM,   0x6000, "Save RAM"},
    {0,                       0x0000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  return ok;
}

bool Memory::initSNES()
{
  static const Block blocks[] =
  {
    {RETRO_MEMORY_SYSTEM_RAM, 0x000000, "Work RAM"},
    {RETRO_MEMORY_SAVE_RAM,   0x700000, "Save RAM"},
    {0,                       0x000000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  return ok;
}

bool Memory::initSMS()
{
  static const Block blocks[] =
  {
    {RETRO_MEMORY_SYSTEM_RAM, 0xc000, "Work RAM"},
    {0,                       0x0000, NULL}
  };

  bool ok = initWidthMmap(blocks);
  ok = ok || initWidthMdata(blocks);

  for (auto it = _regions.begin(); it != _regions.end(); ++it)
  {
    if (it->_baseAddr == 0xc000)
    {
      // Adjust Work RAM size because of the Genesis core
      it->_size = 8192;
      break;
    }
  }

  return ok;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016-2017 libfpta authors: please see AUTHORS file.
 *
 * This file is part of libfpta, aka "Fast Positive Tables".
 *
 * libfpta 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.
 *
 * libfpta 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 libfpta.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "details.h"

static __hot fptu_lge fpta_cmp_null(const fptu_field *left) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_null:
    return fptu_eq;
  case fptu_opaque:
    if (payload->other.varlen.opaque_bytes == 0)
      return fptu_eq;
  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_sint(const fptu_field *left, int64_t right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<int64_t>(left->get_payload_uint16(), right);

  case fptu_uint32:
    return fptu_cmp2lge<int64_t>(payload->u32, right);

  case fptu_int32:
    return fptu_cmp2lge<int64_t>(payload->i32, right);

  case fptu_uint64:
    if (right < 0)
      return fptu_gt;
    return fptu_cmp2lge(payload->u64, (uint64_t)right);

  case fptu_int64:
    return fptu_cmp2lge(payload->i64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, (double)right);

  case fptu_fp64:
    return fptu_cmp2lge<double>(payload->fp64, (double)right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_uint(const fptu_field *left, uint64_t right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<uint64_t>(left->get_payload_uint16(), right);

  case fptu_int32:
    if (payload->i32 < 0)
      return fptu_lt;
  case fptu_uint32:
    return fptu_cmp2lge<uint64_t>(payload->u32, right);

  case fptu_int64:
    if (payload->i64 < 0)
      return fptu_lt;
  case fptu_uint64:
    return fptu_cmp2lge(payload->u64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, (double)right);

  case fptu_fp64:
    return fptu_cmp2lge<double>(payload->fp64, (double)right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_fp(const fptu_field *left, double right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<double>(left->get_payload_uint16(), right);

  case fptu_int32:
    return fptu_cmp2lge<double>(payload->i32, right);

  case fptu_uint32:
    return fptu_cmp2lge<double>(payload->u32, right);

  case fptu_int64:
    return fptu_cmp2lge<double>((double)payload->i64, right);

  case fptu_uint64:
    return fptu_cmp2lge<double>((double)payload->u64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, right);

  case fptu_fp64:
    return fptu_cmp2lge(payload->fp64, right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_datetime(const fptu_field *left,
                                        const fptu_time right) {

  if (unlikely(fptu_get_type(left->ct) != fptu_datetime))
    return fptu_ic;

  auto payload = fptu_field_payload(left);
  return fptu_cmp2lge(payload->u64, right.fixedpoint);
}

static __hot fptu_lge fpta_cmp_string(const fptu_field *left, const char *right,
                                      size_t length) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  default:
    return fptu_ic;

  case fptu_cstr:
    return fptu_cmp_str_binary(payload->cstr, right, length);

  case fptu_opaque:
    return fptu_cmp_binary(payload->other.data,
                           payload->other.varlen.opaque_bytes, right, length);
  }
}

static __hot fptu_lge fpta_cmp_binary(const fptu_field *left,
                                      const void *right_data,
                                      size_t right_len) {
  auto payload = fptu_field_payload(left);
  const void *left_data = payload->fixbin;
  size_t left_len;

  switch (fptu_get_type(left->ct)) {
  case fptu_null:
    return (right_len == 0) ? fptu_eq : fptu_ic;

  case fptu_uint16:
  case fptu_uint32:
  case fptu_int32:
  case fptu_fp32:
  case fptu_uint64:
  case fptu_int64:
  case fptu_fp64:
  case fptu_datetime:
    return fptu_ic;

  case fptu_96:
    left_len = 12;
    break;
  case fptu_128:
    left_len = 16;
    break;
  case fptu_160:
    left_len = 20;
    break;
  case fptu_256:
    left_len = 32;
    break;

  case fptu_cstr:
    return fptu_cmp_str_binary(payload->cstr, right_data, right_len);

  case fptu_opaque:
    left_len = payload->other.varlen.opaque_bytes;
    left_data = payload->other.data;
    break;

  case fptu_nested:
  default: /* fptu_farray */
    left_len = units2bytes(payload->other.varlen.brutto);
    left_data = payload->other.data;
    break;
  }

  return fptu_cmp_binary(left_data, left_len, right_data, right_len);
}

//----------------------------------------------------------------------------

static __hot fptu_lge fpta_filter_cmp(const fptu_field *pf,
                                      const fpta_value &right) {
  if ((unlikely(pf == nullptr)))
    return (right.type == fpta_null) ? fptu_eq : fptu_ic;

  switch (right.type) {
  case fpta_null:
    return fpta_cmp_null(pf);

  case fpta_signed_int:
    return fpta_cmp_sint(pf, right.sint);

  case fpta_unsigned_int:
    return fpta_cmp_uint(pf, right.uint);

  case fpta_float_point:
    return fpta_cmp_fp(pf, right.fp);

  case fpta_datetime:
    return fpta_cmp_datetime(pf, right.datetime);

  case fpta_string:
    return fpta_cmp_string(pf, right.str, right.binary_length);

  case fpta_binary:
  case fpta_shoved:
    return fpta_cmp_binary(pf, right.binary_data, right.binary_length);

  default:
    assert(false);
    return fptu_ic;
  }
}

fptu_lge __fpta_filter_cmp(const fptu_field *pf, const fpta_value *right) {
  return fpta_filter_cmp(pf, *right);
}

__hot bool fpta_filter_match(const fpta_filter *fn, fptu_ro tuple) {

tail_recursion:

  if (unlikely(fn == nullptr))
    // empty filter
    return true;

  switch (fn->type) {
  case fpta_node_not:
    return !fpta_filter_match(fn->node_not, tuple);

  case fpta_node_or:
    if (fpta_filter_match(fn->node_or.a, tuple))
      return true;
    fn = fn->node_or.b;
    goto tail_recursion;

  case fpta_node_and:
    if (!fpta_filter_match(fn->node_and.a, tuple))
      return false;
    fn = fn->node_and.b;
    goto tail_recursion;

  case fpta_node_fncol:
    return fn->node_fncol.predicate(
        fptu_lookup_ro(tuple, fn->node_fncol.column_id->column.num,
                       fpta_id2type(fn->node_fncol.column_id)),
        fn->node_fncol.arg);

  case fpta_node_fnrow:
    return fn->node_fnrow.predicate(&tuple, fn->node_fnrow.context,
                                    fn->node_fnrow.arg);

  default:
    int cmp_bits =
        fpta_filter_cmp(fptu_lookup_ro(tuple, fn->node_cmp.left_id->column.num,
                                       fpta_id2type(fn->node_cmp.left_id)),
                        fn->node_cmp.right_value);

    return (cmp_bits & fn->type) != 0;
  }
}

//----------------------------------------------------------------------------

bool fpta_filter_validate(const fpta_filter *filter) {
  int rc;

tail_recursion:

  if (!filter)
    return true;

  switch (filter->type) {
  default:
    return false;

  case fpta_node_fncol:
    rc = fpta_id_validate(filter->node_fncol.column_id, fpta_column);
    if (unlikely(rc != FPTA_SUCCESS))
      return false;
    if (unlikely(!filter->node_fncol.predicate))
      return false;
    return true;

  case fpta_node_fnrow:
    if (unlikely(!filter->node_fnrow.predicate))
      return false;
    return true;

  case fpta_node_not:
    filter = filter->node_not;
    goto tail_recursion;

  case fpta_node_or:
  case fpta_node_and:
    if (unlikely(!fpta_filter_validate(filter->node_and.a)))
      return false;
    filter = filter->node_and.b;
    goto tail_recursion;

  case fpta_node_lt:
  case fpta_node_gt:
  case fpta_node_le:
  case fpta_node_ge:
  case fpta_node_eq:
  case fpta_node_ne:
    rc = fpta_id_validate(filter->node_cmp.left_id, fpta_column);
    if (unlikely(rc != FPTA_SUCCESS))
      return false;

    if (unlikely(filter->node_cmp.right_value.type == fpta_begin ||
                 filter->node_cmp.right_value.type == fpta_end))
      return false;

    /* FIXME: проверка на совместимость типов node_cmp.left_id и
     * node_cmp.right_value*/
    return true;
  }
}

//----------------------------------------------------------------------------

int fpta_name_refresh_filter(fpta_txn *txn, fpta_name *table_id,
                             fpta_filter *filter) {
tail_recursion:
  int rc = FPTA_SUCCESS;
  if (filter) {
    switch (filter->type) {
    default:
      break;

    case fpta_node_fncol:
      rc =
          fpta_name_refresh_couple(txn, table_id, filter->node_fncol.column_id);
      break;

    case fpta_node_not:
      filter = filter->node_not;
      goto tail_recursion;

    case fpta_node_or:
    case fpta_node_and:
      rc = fpta_name_refresh_filter(txn, table_id, filter->node_and.a);
      if (unlikely(rc != FPTA_SUCCESS))
        break;
      filter = filter->node_and.b;
      goto tail_recursion;

    case fpta_node_lt:
    case fpta_node_gt:
    case fpta_node_le:
    case fpta_node_ge:
    case fpta_node_eq:
    case fpta_node_ne:
      rc = fpta_name_refresh_couple(txn, table_id, filter->node_cmp.left_id);
      break;
    }
  }

  return rc;
}
<commit_msg>fpta: check/disallow composite-columns in fpta_filter_validate().<commit_after>/*
 * Copyright 2016-2017 libfpta authors: please see AUTHORS file.
 *
 * This file is part of libfpta, aka "Fast Positive Tables".
 *
 * libfpta 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.
 *
 * libfpta 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 libfpta.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "details.h"

static __hot fptu_lge fpta_cmp_null(const fptu_field *left) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_null /* here is/should not a composite column/index */:
    return fptu_eq;
  case fptu_opaque:
    if (payload->other.varlen.opaque_bytes == 0)
      return fptu_eq;
  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_sint(const fptu_field *left, int64_t right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<int64_t>(left->get_payload_uint16(), right);

  case fptu_uint32:
    return fptu_cmp2lge<int64_t>(payload->u32, right);

  case fptu_int32:
    return fptu_cmp2lge<int64_t>(payload->i32, right);

  case fptu_uint64:
    if (right < 0)
      return fptu_gt;
    return fptu_cmp2lge(payload->u64, (uint64_t)right);

  case fptu_int64:
    return fptu_cmp2lge(payload->i64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, (double)right);

  case fptu_fp64:
    return fptu_cmp2lge<double>(payload->fp64, (double)right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_uint(const fptu_field *left, uint64_t right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<uint64_t>(left->get_payload_uint16(), right);

  case fptu_int32:
    if (payload->i32 < 0)
      return fptu_lt;
  case fptu_uint32:
    return fptu_cmp2lge<uint64_t>(payload->u32, right);

  case fptu_int64:
    if (payload->i64 < 0)
      return fptu_lt;
  case fptu_uint64:
    return fptu_cmp2lge(payload->u64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, (double)right);

  case fptu_fp64:
    return fptu_cmp2lge<double>(payload->fp64, (double)right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_fp(const fptu_field *left, double right) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  case fptu_uint16:
    return fptu_cmp2lge<double>(left->get_payload_uint16(), right);

  case fptu_int32:
    return fptu_cmp2lge<double>(payload->i32, right);

  case fptu_uint32:
    return fptu_cmp2lge<double>(payload->u32, right);

  case fptu_int64:
    return fptu_cmp2lge<double>((double)payload->i64, right);

  case fptu_uint64:
    return fptu_cmp2lge<double>((double)payload->u64, right);

  case fptu_fp32:
    return fptu_cmp2lge<double>(payload->fp32, right);

  case fptu_fp64:
    return fptu_cmp2lge(payload->fp64, right);

  default:
    return fptu_ic;
  }
}

static __hot fptu_lge fpta_cmp_datetime(const fptu_field *left,
                                        const fptu_time right) {

  if (unlikely(fptu_get_type(left->ct) != fptu_datetime))
    return fptu_ic;

  auto payload = fptu_field_payload(left);
  return fptu_cmp2lge(payload->u64, right.fixedpoint);
}

static __hot fptu_lge fpta_cmp_string(const fptu_field *left, const char *right,
                                      size_t length) {
  auto payload = fptu_field_payload(left);

  switch (fptu_get_type(left->ct)) {
  default:
    return fptu_ic;

  case fptu_cstr:
    return fptu_cmp_str_binary(payload->cstr, right, length);

  case fptu_opaque:
    return fptu_cmp_binary(payload->other.data,
                           payload->other.varlen.opaque_bytes, right, length);
  }
}

static __hot fptu_lge fpta_cmp_binary(const fptu_field *left,
                                      const void *right_data,
                                      size_t right_len) {
  auto payload = fptu_field_payload(left);
  const void *left_data = payload->fixbin;
  size_t left_len;

  switch (fptu_get_type(left->ct)) {
  case fptu_null /* here is/should not a composite column/index */:
    return (right_len == 0) ? fptu_eq : fptu_ic;

  case fptu_uint16:
  case fptu_uint32:
  case fptu_int32:
  case fptu_fp32:
  case fptu_uint64:
  case fptu_int64:
  case fptu_fp64:
  case fptu_datetime:
    return fptu_ic;

  case fptu_96:
    left_len = 12;
    break;
  case fptu_128:
    left_len = 16;
    break;
  case fptu_160:
    left_len = 20;
    break;
  case fptu_256:
    left_len = 32;
    break;

  case fptu_cstr:
    return fptu_cmp_str_binary(payload->cstr, right_data, right_len);

  case fptu_opaque:
    left_len = payload->other.varlen.opaque_bytes;
    left_data = payload->other.data;
    break;

  case fptu_nested:
  default: /* fptu_farray */
    left_len = units2bytes(payload->other.varlen.brutto);
    left_data = payload->other.data;
    break;
  }

  return fptu_cmp_binary(left_data, left_len, right_data, right_len);
}

//----------------------------------------------------------------------------

static __hot fptu_lge fpta_filter_cmp(const fptu_field *pf,
                                      const fpta_value &right) {
  if ((unlikely(pf == nullptr)))
    return (right.type == fpta_null) ? fptu_eq : fptu_ic;

  switch (right.type) {
  case fpta_null:
    return fpta_cmp_null(pf);

  case fpta_signed_int:
    return fpta_cmp_sint(pf, right.sint);

  case fpta_unsigned_int:
    return fpta_cmp_uint(pf, right.uint);

  case fpta_float_point:
    return fpta_cmp_fp(pf, right.fp);

  case fpta_datetime:
    return fpta_cmp_datetime(pf, right.datetime);

  case fpta_string:
    return fpta_cmp_string(pf, right.str, right.binary_length);

  case fpta_binary:
  case fpta_shoved:
    return fpta_cmp_binary(pf, right.binary_data, right.binary_length);

  default:
    assert(false);
    return fptu_ic;
  }
}

fptu_lge __fpta_filter_cmp(const fptu_field *pf, const fpta_value *right) {
  return fpta_filter_cmp(pf, *right);
}

__hot bool fpta_filter_match(const fpta_filter *fn, fptu_ro tuple) {

tail_recursion:

  if (unlikely(fn == nullptr))
    // empty filter
    return true;

  switch (fn->type) {
  case fpta_node_not:
    return !fpta_filter_match(fn->node_not, tuple);

  case fpta_node_or:
    if (fpta_filter_match(fn->node_or.a, tuple))
      return true;
    fn = fn->node_or.b;
    goto tail_recursion;

  case fpta_node_and:
    if (!fpta_filter_match(fn->node_and.a, tuple))
      return false;
    fn = fn->node_and.b;
    goto tail_recursion;

  case fpta_node_fncol:
    return fn->node_fncol.predicate(
        fptu_lookup_ro(tuple, fn->node_fncol.column_id->column.num,
                       fpta_id2type(fn->node_fncol.column_id)),
        fn->node_fncol.arg);

  case fpta_node_fnrow:
    return fn->node_fnrow.predicate(&tuple, fn->node_fnrow.context,
                                    fn->node_fnrow.arg);

  default:
    int cmp_bits =
        fpta_filter_cmp(fptu_lookup_ro(tuple, fn->node_cmp.left_id->column.num,
                                       fpta_id2type(fn->node_cmp.left_id)),
                        fn->node_cmp.right_value);

    return (cmp_bits & fn->type) != 0;
  }
}

//----------------------------------------------------------------------------

bool fpta_filter_validate(const fpta_filter *filter) {
  int rc;

tail_recursion:

  if (!filter)
    return true;

  switch (filter->type) {
  default:
    return false;

  case fpta_node_fncol:
    rc = fpta_id_validate(filter->node_fncol.column_id, fpta_column);
    if (unlikely(rc != FPTA_SUCCESS))
      return false;
    if (unlikely(fpta_column_is_composite(filter->node_fncol.column_id)))
      return false;
    if (unlikely(!filter->node_fncol.predicate))
      return false;
    return true;

  case fpta_node_fnrow:
    if (unlikely(!filter->node_fnrow.predicate))
      return false;
    return true;

  case fpta_node_not:
    filter = filter->node_not;
    goto tail_recursion;

  case fpta_node_or:
  case fpta_node_and:
    if (unlikely(!fpta_filter_validate(filter->node_and.a)))
      return false;
    filter = filter->node_and.b;
    goto tail_recursion;

  case fpta_node_lt:
  case fpta_node_gt:
  case fpta_node_le:
  case fpta_node_ge:
  case fpta_node_eq:
  case fpta_node_ne:
    rc = fpta_id_validate(filter->node_cmp.left_id, fpta_column);
    if (unlikely(rc != FPTA_SUCCESS))
      return false;
    if (unlikely(fpta_column_is_composite(filter->node_cmp.left_id)))
      return false;

    if (unlikely(filter->node_cmp.right_value.type == fpta_begin ||
                 filter->node_cmp.right_value.type == fpta_end))
      return false;

    /* FIXME: проверка на совместимость типов node_cmp.left_id и
     * node_cmp.right_value*/
    return true;
  }
}

//----------------------------------------------------------------------------

int fpta_name_refresh_filter(fpta_txn *txn, fpta_name *table_id,
                             fpta_filter *filter) {
tail_recursion:
  int rc = FPTA_SUCCESS;
  if (filter) {
    switch (filter->type) {
    default:
      break;

    case fpta_node_fncol:
      rc =
          fpta_name_refresh_couple(txn, table_id, filter->node_fncol.column_id);
      break;

    case fpta_node_not:
      filter = filter->node_not;
      goto tail_recursion;

    case fpta_node_or:
    case fpta_node_and:
      rc = fpta_name_refresh_filter(txn, table_id, filter->node_and.a);
      if (unlikely(rc != FPTA_SUCCESS))
        break;
      filter = filter->node_and.b;
      goto tail_recursion;

    case fpta_node_lt:
    case fpta_node_gt:
    case fpta_node_le:
    case fpta_node_ge:
    case fpta_node_eq:
    case fpta_node_ne:
      rc = fpta_name_refresh_couple(txn, table_id, filter->node_cmp.left_id);
      break;
    }
  }

  return rc;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010 The Native Client 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 <assert.h>

#include "native_client/src/trusted/plugin/ppapi/browser_interface_ppapi.h"

#include "native_client/src/include/checked_cast.h"
#include "native_client/src/include/nacl_elf.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/trusted/plugin/api_defines.h"
#include "native_client/src/trusted/plugin/ppapi/scriptable_handle_ppapi.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/var.h"

using nacl::assert_cast;

namespace {

bool GetWindow(plugin::InstanceIdentifier instance_id, pp::Var* window) {
  pp::Instance* instance = plugin::InstanceIdentifierToPPInstance(instance_id);
  *window = instance->GetWindowObject();
  return !window->is_void();
}

}  // namespace

namespace plugin {

uintptr_t BrowserInterfacePpapi::StringToIdentifier(const nacl::string& str) {
  StringToIdentifierMap::iterator iter = string_to_identifier_map_.find(str);
  if (iter == string_to_identifier_map_.end()) {
    uintptr_t id = reinterpret_cast<uintptr_t>(str.c_str());
    string_to_identifier_map_.insert(make_pair(str, id));
    identifier_to_string_map_.insert(make_pair(id, str));
    return id;
  }
  return string_to_identifier_map_[str];
}

nacl::string BrowserInterfacePpapi::IdentifierToString(uintptr_t ident) {
  assert(identifier_to_string_map_.find(ident) !=
         identifier_to_string_map_.end());
  return identifier_to_string_map_[ident];
}

bool BrowserInterfacePpapi::Alert(InstanceIdentifier instance_id,
                                  const nacl::string& text) {
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var exception;
  window.Call("alert", text, &exception);
  return exception.is_void();
}

bool BrowserInterfacePpapi::EvalString(InstanceIdentifier instance_id,
                                       const nacl::string& expression) {
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var exception;
  window.Call("eval", expression, &exception);
  return exception.is_void();
}

bool BrowserInterfacePpapi::GetOrigin(InstanceIdentifier instance_id,
                                      nacl::string* origin) {
  const nacl::string kUnknownOrigin = "";
  *origin = kUnknownOrigin;
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var location = window.GetProperty("location");
  if (location.is_object()) {
    pp::Var href = location.GetProperty("href");
    if (!href.is_string()) {
      *origin = href.AsString();
    }
  }
  return (kUnknownOrigin != *origin);
}

ScriptableHandle* BrowserInterfacePpapi::NewScriptableHandle(
    PortableHandle* handle) {
  return ScriptableHandlePpapi::New(handle);
}

pp::Instance* InstanceIdentifierToPPInstance(InstanceIdentifier instance_id) {
  return reinterpret_cast<pp::Instance*>(assert_cast<intptr_t>(instance_id));
}

InstanceIdentifier PPInstanceToInstanceIdentifier(pp::Instance* instance) {
  return assert_cast<InstanceIdentifier>(reinterpret_cast<intptr_t>(instance));
}

}  // namespace plugin
<commit_msg>Fix GetOrigin in the PPAPI browser interface implementation. AsString() should be called on a Var that of string type, not of non-string type.  Review URL: http://codereview.chromium.org/2825064<commit_after>/*
 * Copyright 2010 The Native Client 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 <assert.h>

#include "native_client/src/trusted/plugin/ppapi/browser_interface_ppapi.h"

#include "native_client/src/include/checked_cast.h"
#include "native_client/src/include/nacl_elf.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/trusted/plugin/api_defines.h"
#include "native_client/src/trusted/plugin/ppapi/scriptable_handle_ppapi.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/var.h"

using nacl::assert_cast;

namespace {

bool GetWindow(plugin::InstanceIdentifier instance_id, pp::Var* window) {
  pp::Instance* instance = plugin::InstanceIdentifierToPPInstance(instance_id);
  *window = instance->GetWindowObject();
  return !window->is_void();
}

}  // namespace

namespace plugin {

uintptr_t BrowserInterfacePpapi::StringToIdentifier(const nacl::string& str) {
  StringToIdentifierMap::iterator iter = string_to_identifier_map_.find(str);
  if (iter == string_to_identifier_map_.end()) {
    uintptr_t id = reinterpret_cast<uintptr_t>(str.c_str());
    string_to_identifier_map_.insert(make_pair(str, id));
    identifier_to_string_map_.insert(make_pair(id, str));
    return id;
  }
  return string_to_identifier_map_[str];
}

nacl::string BrowserInterfacePpapi::IdentifierToString(uintptr_t ident) {
  assert(identifier_to_string_map_.find(ident) !=
         identifier_to_string_map_.end());
  return identifier_to_string_map_[ident];
}

bool BrowserInterfacePpapi::Alert(InstanceIdentifier instance_id,
                                  const nacl::string& text) {
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var exception;
  window.Call("alert", text, &exception);
  return exception.is_void();
}

bool BrowserInterfacePpapi::EvalString(InstanceIdentifier instance_id,
                                       const nacl::string& expression) {
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var exception;
  window.Call("eval", expression, &exception);
  return exception.is_void();
}

bool BrowserInterfacePpapi::GetOrigin(InstanceIdentifier instance_id,
                                      nacl::string* origin) {
  const nacl::string kUnknownOrigin = "";
  *origin = kUnknownOrigin;
  pp::Var window;
  if (!GetWindow(instance_id, &window)) {
    return false;
  }
  pp::Var location = window.GetProperty("location");
  if (location.is_object()) {
    pp::Var href = location.GetProperty("href");
    if (href.is_string()) {
      *origin = href.AsString();
    }
  }
  return (kUnknownOrigin != *origin);
}

ScriptableHandle* BrowserInterfacePpapi::NewScriptableHandle(
    PortableHandle* handle) {
  return ScriptableHandlePpapi::New(handle);
}

pp::Instance* InstanceIdentifierToPPInstance(InstanceIdentifier instance_id) {
  return reinterpret_cast<pp::Instance*>(assert_cast<intptr_t>(instance_id));
}

InstanceIdentifier PPInstanceToInstanceIdentifier(pp::Instance* instance) {
  return assert_cast<InstanceIdentifier>(reinterpret_cast<intptr_t>(instance));
}

}  // namespace plugin
<|endoftext|>