language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
340
3.796875
4
[]
no_license
var array = [1,2,3,3,4,6,6] function duplicate(array){ for(let i=0;i<=array.length;i++){ let count = 0; for(let j=0;j<array.length;j++){ if(array[i] ==array[j]){ count++; } } if(count >1){ console.log(array[i]) } } } duplicate(array)
Shell
UTF-8
3,858
4.09375
4
[ "Unlicense" ]
permissive
#!/bin/sh marker=********** logFile=logs/log.txt key=$(($RANDOM%99999+10000)) isLogFileFound=false FILEFOLDERSIZE=0k verifyLogFile () { if [ -f "$1" ]; then isLogFileFound=true else isLogFileFound=false now=$(date +"%Y-%m-%d %T") echo "${now}* logFile '${logFile}' does not exist." fi } verifyLogFile $logFile addLog() { now=$(date +"%Y-%m-%d %T") if [[ $isLogFileFound == true ]]; then echo "${now} $1" echo "${now} $key $1" >> $logFile else echo "${now}* $1" # * represent log file is not found fi } verifyOldData() { if [[ $1 = "zzzzzzzzzz" ]]; then sourceDir="" else sourceDir=$1 fi if [[ $2 = "zzzzzzzzzz" ]]; then destinationDir="" else destinationDir=$2 fi if [[ $3 = "zzzzzzzzzz" ]]; then fileFolderName="" else fileFolderName=$3 fi destination=${destinationDir}${fileFolderName} source=${sourceDir}${fileFolderName} if [[ -d "${destination}" ]]; then # rm -rf ${destination} elif [[ -f "${destination}" ]]; then # rm ${destination} else if [[ -f ${source} ]]; then addLog "Old File '${destination}' does not exist" elif [[ -d ${source} ]]; then addLog "Old Folder '${destination}' does not exist" else addLog "Old File/Folder '${destination}' does not exist" fi fi } updateFILEFOLDERSIZE () { if [[ $1 = "zzzzzzzzzz" ]]; then s="" else s=$1 fi if [[ $2 = "zzzzzzzzzz" ]]; then f="" else f=$2 fi if [[ -d ${s}${f} ]]; then FILEFOLDERSIZE=$(du -sh ${s}${f}) elif [[ -f ${s}${f} ]]; then FILEFOLDERSIZE=$(du -sh ${s}${f}) fi i=0 for index in $(echo $FILEFOLDERSIZE | tr "" "\n") do if [[ $i > 0 ]]; then continue fi FILEFOLDERSIZE=$index i="`expr $i + 1`" done } sourceDir=() name=() destinationDir=() updateSource () { input="file_data.txt" lineNumber=0 if [[ !(-f $input) ]]; then addLog "Input source file '$input' does not exist." return fi while read line; do if [[ $lineNumber < 1 ]]; then for word in $(echo $line | tr " " "\n"); do logFile=$word break done lineNumber=$((lineNumber+1)) verifyLogFile $logFile continue fi for word in $(echo $line | tr " " "\n"); do lineData+=($word) done destinationDir+=(${lineData[0]}) name+=(${lineData[1]}) sourceDir+=(${lineData[2]}) lineData=() lineNumber=$((lineNumber+1)) done < "$input" } addLog "${marker} Copy start ${marker}" addLog "Current directory: $(pwd)" updateSource loopEndCount=$((${#destinationDir[*]})) for ((c=0; c<$loopEndCount; c++)) do s=${sourceDir[$c]} d=${destinationDir[$c]} f=${name[$c]} ss=${s} dd=${d} ff=${f} if [ -d "$d" ]; then if [[ $ss = "" ]]; then ss="zzzzzzzzzz" # 10 times z fi if [[ $dd = "" ]]; then dd="zzzzzzzzzz" fi if [[ $ff = "" ]]; then ff="zzzzzzzzzz" fi verifyOldData ${ss} ${dd} ${ff} updateFILEFOLDERSIZE ${ss} ${ff} size=${FILEFOLDERSIZE} addLog "Copying from '${s}${f}' size ${size} to '${d}'" cp -r ${s}${f} ${d} # if [[ -f ${s}${f} ]]; then # size=$(wc -c <${s}${f}) # Get file size in bytes # if [[ $size -lt 1000000 ]]; then # size="`expr $size / 1000`kb" # elif [[ $size -lt 1000000000 ]]; then # size="`expr $size / 1000000`mb" # else # size="`expr $size / 1000000000`gb" # fi # addLog "Copying files size ${size} from '${s}${f}' to '${d}'" # cp ${s}${f} ${d} # else # addLog "Copying files size ${size} from '${s}${f}' to '${d}'" # cp -r ${s}${f} ${d} # fi else addLog "Destination directory '${d}' does not exist." fi done addLog "${marker} COPY END ${marker}" read -p "Press enter to exit."
Markdown
UTF-8
2,553
3.25
3
[ "MIT" ]
permissive
# Material dashboard ## Getting started Per aggiungere Angular/material, digitare il seguente comando: `ng add @angular/material` ## Creare una dashboard in stile material Per generare il componente utilizzando il Material design, digitare il seguente comando: `ng generate @angular/material:material-dashboard --name dashboard` Per esempio, utilizzando un approccio tipico a quello della creazione della dashboard, si avrà una bacheca simile a questa: Basterà utilizzare il sistema a griglia fornito dal Material Design, specificando quante colonne e a quale riga inserire i vari componenti, come visibile dal codice di seguito: src/app/dashboard.component.ts ``` import { Component } from '@angular/core'; @Component({ selector: 'material-dashboard', templateUrl: './material-dashboard.component.html', styleUrls: ['./material-dashboard.component.css'] }) export class MaterialDashboardComponent { // Number of cards to be generated with column and rows to be covered cards = [ { title: 'Card 1', cols: 2, rows: 1 }, { title: 'Card 2', cols: 1, rows: 1 }, { title: 'Card 3', cols: 1, rows: 2 }, { title: 'Card 4', cols: 1, rows: 1 } ]; } ``` src/app/dashboard.component.html ``` <div class="grid-container"> <h1 class="mat-h1">Welcome dashboard</h1> <mat-grid-list cols="2" rowHeight="400px"> <mat-grid-tile *ngFor="let card of cards" [colspan]="card.cols" [rowspan]="card.rows"> <mat-card class="dashboard-card"> <mat-card-header> <mat-card-title> {{card.title}} <button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu" xPosition="before"> <button mat-menu-item>Expand</button> <button mat-menu-item>Remove</button> </mat-menu> </mat-card-title> </mat-card-header> <mat-card-content class="dashboard-card-content"> <div>Lorem Ipsum</div> </mat-card-content> </mat-card> </mat-grid-tile> </mat-grid-list> </div> ``` src/app/dashboard.component.css ``` .grid-container { margin: 20px; } .dashboard-card { position: absolute; top: 15px; left: 15px; right: 15px; bottom: 15px; } .more-button { position: absolute; top: 5px; right: 10px; } .dashboard-card-content { text-align: center; } ```
Python
UTF-8
4,717
2.84375
3
[]
no_license
import pygame class MazeRender(): def __init__(self, screem_maze, terminal_maze, screem_maze_size, sizes, screem_maze_solve, terminal_maze_solve): self.screem_maze = screem_maze self.terminal_maze = terminal_maze self.screem_maze_size = screem_maze_size self.sizes = sizes self.screem_maze_solve = screem_maze_solve self.terminal_maze_solve = terminal_maze_solve def draw_screem_maze(self, start, end, colors, window): for walls in self.screem_maze: for wall in walls: wall.draw_wall(window) if(wall.get_index() == start): x, y = wall.get_position() pixel_size = self.sizes[self.screem_maze_size]['pixel_size'] pygame.draw.circle(window, colors['BLUE'], (x + pixel_size // 2, y + pixel_size // 2), 7) if(wall.get_index() == end): x, y = wall.get_position() pixel_size = self.sizes[self.screem_maze_size]['pixel_size'] pygame.draw.circle(window, colors['RED'], (x + pixel_size // 2, y + pixel_size // 2), 7) def wall_list(self): wall_list = [] for walls in self.screem_maze: for wall in walls: wall_list.append(wall) return wall_list def verifiy_direction_path(self, frist_wall_position, second_wall_position, maze): if (second_wall_position[0] == frist_wall_position[0] and second_wall_position[1] >= frist_wall_position[1]): # RIGHT return 'RIGHT' elif(second_wall_position[0] == frist_wall_position[0] and second_wall_position[1] <= frist_wall_position[1]): # LEFT return 'LEFT' elif(second_wall_position[0] <= frist_wall_position[0] and second_wall_position[1] == frist_wall_position[1]): # TOP return 'TOP' elif(second_wall_position[0] >= frist_wall_position[0] and second_wall_position[1] == frist_wall_position[1]): # BOTTOM return 'BOTTOM' else: print(f'>>> verify-direction-error >>> fst:{frist_wall_position} - snd:{second_wall_position}') print(maze) print('\n') def draw_screem_maze_solve(self, start, end, colors, window): pixel_size = self.sizes[self.screem_maze_size]['pixel_size'] for i in range(1, len(self.screem_maze_solve)): frist = self.screem_maze_solve[i-1] second = self.screem_maze_solve[i] frist_wall = None second_wall = None for wall in self.wall_list(): wall_pos = wall.get_index() if(wall_pos == frist): frist_wall = wall elif(wall_pos == second): second_wall = wall else: continue direction = self.verifiy_direction_path(frist, second, self.screem_maze_solve) if(frist_wall is not None): frist_wall.draw_path(direction, window) if(frist_wall is not None and frist_wall.get_index() == start): x, y = frist_wall.get_position() pygame.draw.circle(window, colors['BLUE'], (x + pixel_size//2, y + pixel_size//2), 7) if(second_wall is not None and second_wall.get_index() == end): x, y = second_wall.get_position() pygame.draw.circle(window, colors['RED'], (x + pixel_size//2, y + pixel_size//2), 7) def draw_terminal_maze(self, show_solve=False, start=None, end=None): RED = "\033[1;31m" BLUE = "\033[1;34m" GREEN = "\033[0;32m" RESET = "\033[0;0m" REVERSE = "\033[;7m" if (not show_solve): print(f'Maze ({self.screem_maze_size[1]}x{self.screem_maze_size[0]})\n') else: print(f'Maze ({self.screem_maze_size[1]}x{self.screem_maze_size[0]}) - Solve\n') for i in range(0, len(self.terminal_maze)): for j in range(0, len(self.terminal_maze[i])): pixel = self.terminal_maze[i][j] if((i,j) == start): print(BLUE + '1 ' + RESET, end='') elif((i,j) == end): print(GREEN + '1 ' + RESET, end='') elif((i,j) in self.terminal_maze_solve and show_solve): print(REVERSE + '1 ' + RESET, end='') else: if(not pixel): print(RED + '0 ' + RESET, end='') else: print('1 ' + RESET, end='') print('' + RESET) print('\n') if __name__ == "__main__" : print('MazeRender')
PHP
UTF-8
1,878
2.59375
3
[ "Apache-2.0" ]
permissive
<?php namespace Lydia\Services; use Lydia\Entity\Credentials; use Exception; use Lydia\Entity\User; /** * Class Auth * * See https://homologation.lydia-app.com/doc/api/#api-Auth * */ class Auth extends Requestor { /** * Payments constructor. * @param Credentials $credentials * @param $url */ public function __construct(Credentials $credentials,$user,$url) { $url .= 'auth/'; parent::__construct($credentials,$user,$url); } /** * @param $phone * @param $password * @param array $data * * @return User * * @throws Exception */ public function login($phone,$password,$data = array()) { $data = array_merge(array( 'notify' => "no", 'phone' => $phone, 'password'=> $password ),$data); $response = $this->post('login',$data); return new User($response['user']); } /** * @param array $data * * @return User * * @throws Exception */ public function register($data = array()) { $data['vendor_token'] = $this->credentials->public_key; $response = $this->post('register',$data); return new User($response['user']); } /** * * Creates a P2P Account * * @param array $data * @return User * @throws Exception */ public function createAccount($data = array()) { $data['provider_token'] = $this->credentials->provider_token; $response = $this->post('create_account',$data); return new User($response['user']); } public function vendorToken() { return $this->post('vendortoken',array( 'vendor_id' => $this->credentials->public_key, 'vendor_token' => $this->credentials->private_key, )); } }
C#
UTF-8
7,807
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using PostCodes.IO.Wrapper; namespace LifeInsurance { public class Calculator { private readonly ILocationFinder _locationFinder; private Dictionary<BasePrice, decimal> _basePremiums; private Dictionary<ExcerciseBracket, decimal> _excercisePremiums; private Dictionary<string, decimal> _locationPremiums; public readonly decimal MINIMUM_PRICE = 50.00M; private const decimal DEFAULT_REGIONAL_HEALTH_INDEX = 100; private const int PREMIUM_FOR_SMOKERS = 300; private const int PREMIUM_FOR_PARENTS = 50; private const int PREMIUM_FOR_NON_PARENTS = 0; private const int PREMIUM_FOR_NON_SMOKERS = 0; public Calculator(ILocationFinder locationFinder) { _locationFinder = locationFinder; InitialiseeBasePriceLookup(); InitialiseExcercisePremiumLookup(); InitialiseLocationsPremiumLookup(); } private void InitialiseLocationsPremiumLookup() { _locationPremiums = new Dictionary<string, decimal> { {"england", 0}, {"wales", -100}, {"scotland", 200}, {"northern ireland", 75}, {"ireland", 50} }; } private void InitialiseExcercisePremiumLookup() { _excercisePremiums = new Dictionary<ExcerciseBracket, decimal> { {new ExcerciseBracket(0, 0), +20}, {new ExcerciseBracket(1, 2), 0}, {new ExcerciseBracket(3, 5), -30}, {new ExcerciseBracket(6, 8), -50}, {new ExcerciseBracket(9, int.MaxValue), +50} }; } private void InitialiseeBasePriceLookup() { _basePremiums = new Dictionary<BasePrice, decimal> { {new BasePrice(0, 18, Gender.Male), (decimal) 150.00}, {new BasePrice(0, 18, Gender.Female), (decimal) 100.00}, {new BasePrice(19, 24, Gender.Male), (decimal) 180.00}, {new BasePrice(19, 24, Gender.Female), (decimal) 165.00}, {new BasePrice(25, 34, Gender.Male), (decimal) 200.00}, {new BasePrice(25, 34, Gender.Female), (decimal) 180.00}, {new BasePrice(35, 44, Gender.Male), (decimal) 250.00}, {new BasePrice(35, 44, Gender.Female), (decimal) 225.00}, {new BasePrice(45, 60, Gender.Male), (decimal) 320.00}, {new BasePrice(45, 60, Gender.Female), (decimal) 315.00}, {new BasePrice(61, Int32.MaxValue, Gender.Male), (decimal) 500.00}, {new BasePrice(61, Int32.MaxValue, Gender.Female), (decimal) 485.00} }; } public LifeQuote CalculateLifeQuote(Risk customerRisk) { var customerAge = CalculateCustomerAgeFromDOB(customerRisk.DateOfBirth); var basePrice = GetBasePrice(customerAge, customerRisk.Gender); var regionalHealthIndex = GetRegionalHealthIndex(customerRisk.Postcode); var childrenPremium = GetChildrenPremium(customerRisk.HaveChildren); var smokerPremium = GetSmokerPremium(customerRisk.Smoker); var excercisePremium = GetExcercisePremium(customerRisk.HoursOfExercisePerWeek); var price = CalculateTotalPremium(basePrice, regionalHealthIndex, childrenPremium, smokerPremium, excercisePremium); return new LifeQuote(price); } private decimal CalculateTotalPremium(decimal basePrice, decimal regionalHealthIndex, decimal childrenPremium, decimal smokerPremium, decimal excercisePremium) { var price = basePrice + regionalHealthIndex; price += ModifyPriceByPercentage(price, childrenPremium); price += ModifyPriceByPercentage(price, smokerPremium); price += ModifyPriceByPercentage(price, excercisePremium); return ApplyMinimumPriceRule(price); } private static decimal ModifyPriceByPercentage(decimal originalPrice, decimal percentage) { return (originalPrice/100)*percentage; } private decimal ApplyMinimumPriceRule(decimal price) { if (price < MINIMUM_PRICE) price = MINIMUM_PRICE; return price; } private decimal GetExcercisePremium(int hoursOfExercisePerWeek) { var excercisePremium = _excercisePremiums.Where(excerciseBracket => excerciseBracket.Key.MinHours <= hoursOfExercisePerWeek && excerciseBracket.Key.MaxHours >= hoursOfExercisePerWeek); if (!excercisePremium.Any()) throw new CalculatorException($"No matching Excercise Bracket was found for {hoursOfExercisePerWeek} hourse of excerise per week."); return excercisePremium.ElementAt(0).Value; } private decimal GetSmokerPremium(bool smoker) { return smoker ? PREMIUM_FOR_SMOKERS : PREMIUM_FOR_NON_SMOKERS; } private decimal GetChildrenPremium(bool haveChildren) { return haveChildren ? PREMIUM_FOR_PARENTS : PREMIUM_FOR_NON_PARENTS; } private decimal GetRegionalHealthIndex(string postcode) { if (_locationFinder == null) throw new ArgumentNullException("_addressFinder"); var address = new LocationDetails("other"); try { address = _locationFinder.LookupAddressByPostcode(postcode); } catch { // ignored } return LookupRegionalHealthIndexByCountry(address.Country); } private decimal LookupRegionalHealthIndexByCountry(string country) { return _locationPremiums.ContainsKey(country.ToLower()) ? _locationPremiums[country.ToLower()] : DEFAULT_REGIONAL_HEALTH_INDEX; } private decimal GetBasePrice(int customerAge, Gender customerGender) { var basePremium = _basePremiums.Where(basePrice => basePrice.Key.StartingAge <= customerAge && basePrice.Key.EndingAge >= customerAge && basePrice.Key.Gender == customerGender); if (!basePremium.Any()) throw new CalculatorException( $"No base price could be found for the Age and Gender Specified. Age: {customerAge}, Gender{customerGender}"); return basePremium.ElementAt(0).Value; } private int CalculateCustomerAgeFromDOB(DateTime dateOfBirth) { return DateTime.Today.Year - dateOfBirth.Year; } private class ExcerciseBracket { public ExcerciseBracket(int minHours, int maxHours) { MinHours = minHours; MaxHours = maxHours; } public int MinHours { get; } public int MaxHours { get; } } private class BasePrice { public BasePrice(int startingAge, int endAge, Gender gender) { StartingAge = startingAge; EndingAge = endAge; Gender = gender; } public int StartingAge { get; } public int EndingAge { get; } public Gender Gender { get; } } } }
Java
UTF-8
2,220
2.125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2015-2016 - CNRS (Centre National de Recherche Scientifique) * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *******************************************************************************/ package fr.univnantes.termsuite.engines.splitter; import com.google.common.base.MoreObjects; public class Segment implements Comparable<Segment> { private int begin; private int end; /* cached substring of the parent compound */ private String _substring; private String lemma; @Override public int compareTo(Segment o) { return Integer.compare(begin, o.begin); } public Segment(int begin, int end) { super(); this.begin = begin; this.end = end; } public int getBegin() { return begin; } public int getEnd() { return end; } public String getSubstring() { return _substring; } public void setSubstring(String substring) { this._substring = substring; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("substring", _substring) .add("lemma", lemma) .toString(); } public String getLemma() { return lemma; } public void setLemma(String lemma) { this.lemma = lemma; } public static Segment createFromParentString(int begin, int end, String string) { Segment segment = new Segment(begin, end); segment._substring = string.substring(begin, end); return segment; } }
TypeScript
UTF-8
655
2.734375
3
[ "MIT" ]
permissive
import { useContext, useEffect } from 'react'; import FacebookContext from '../components/FacebookContext'; import type { FacebookContextInterface } from '../components/FacebookContext'; export type UseFacebookProps = { lazy?: boolean; }; export default function useFacebook(props: UseFacebookProps = {}): FacebookContextInterface { const { lazy = false } = props; const context: FacebookContextInterface | undefined = useContext(FacebookContext); if (!context) { throw new Error('useFacebook must be used within a FacebookProvider'); } useEffect(() => { if (!lazy) { context.init(); } }, [lazy]); return context; }
Markdown
UTF-8
282
2.671875
3
[]
no_license
# fastpythonfibonacci fastest fibonacci generator in python uses dual assignments at once to cut out the middleman. 10,000 Fibonacci number in less than 4 ms on 2014 hardware: ``` MacBook Air 1.3GHz (2014) $ %timeit -n 100 fib(10000) 100 loops, best of 3: 3.79 ms per loop ```
Java
UTF-8
3,879
3.40625
3
[]
no_license
public class PassByValue { public static void main(String[] commandLine) { // init values that are to be transmogrified int intArg = 17; double doubleArg = 0.5; String stringArg = "A Change Is Gonna Come"; int[] arrayArg = { intArg, intArg, }; OurType ourTypeArg = new OurType(); // before invoking transmogrify System.out.println( ); System.out.println( "in main, before transmogrification"); System.out.println( " intArg= " + intArg ); System.out.println( " doubleArg= " + doubleArg ); System.out.println( " stringArg= " + stringArg ); System.out.println( " arrayArg= " + arrayArg ); System.out.println( " arrayArg[0]= " + arrayArg[0] ); System.out.println( " ourTypeArg= " + ourTypeArg ); System.out.println( " ourTypeArg.value= " + ourTypeArg.value); transmogrify( intArg , doubleArg , stringArg , arrayArg , ourTypeArg ); // what hath transmogrify wrought? System.out.println( ); System.out.println( "in main, after transmogrification"); System.out.println( " intArg= " + intArg ); System.out.println( " doubleArg= " + doubleArg ); System.out.println( " stringArg= " + stringArg ); System.out.println( " arrayArg= " + arrayArg ); System.out.println( " arrayArg[0]= " + arrayArg[0] ); System.out.println( " ourTypeArg= " + ourTypeArg ); System.out.println( " ourTypeArg.value= " + ourTypeArg.value); } private static void transmogrify( int intParam , double doubleParam , String stringParam , int[] arrayParam , OurType ourTypeParam ) { // see copied values System.out.println( ); System.out.println( " in transmogrify, but before transmogrification"); System.out.println( " intParam= " + intParam ); System.out.println( " doubleParam= " + doubleParam ); System.out.println( " stringParam= " + stringParam ); System.out.println( " arrayParam= " + arrayParam ); System.out.println( " arrayParam[0]= " + arrayParam[0] ); System.out.println( " ourTypeParam= " + ourTypeParam ); System.out.println( " ourTypeParam.value= " + ourTypeParam.value); // change the values of params intParam++; doubleParam++; stringParam += " -- Sam Cooke"; arrayParam[0]++; ourTypeParam.value++; // verify change in the parameters System.out.println( ); System.out.println( " in transmogrify, AFTER transmogrification"); System.out.println( " intParam= " + intParam ); System.out.println( " doubleParam= " + doubleParam ); System.out.println( " stringParam= " + stringParam ); System.out.println( " arrayParam= " + arrayParam ); System.out.println( " arrayParam[0]= " + arrayParam[0] ); System.out.println( " ourTypeParam= " + ourTypeParam ); System.out.println( " ourTypeParam.value= " + ourTypeParam.value); } }
JavaScript
UTF-8
167
2.6875
3
[]
no_license
function Inc(){ let i=0; //this.toString = function(){ // return ++i //} } let inc = new Inc(); console.dir(inc); alert(inc) alert(inc) alert(inc+inc+inc)
Python
UTF-8
124
3.3125
3
[]
no_license
def euclid(n, m): if m == 0: return n return euclid(m, n % m) gcd = euclid(123456789, 987654321) print(gcd)
Java
UTF-8
10,916
2.5625
3
[]
no_license
/* JSON API for android appliation */ package com.shekkahmeng.fypapplication.rest; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; import org.json.JSONArray; public class RestAPI { // private static final String urlString = "http://shek.somee.com/Handler1.ashx"; // private static final String urlString = "http://192.168.11.26:8080/Handler1.ashx"; private static final String urlString = "http://conferencerest.apphb.com/Handler1.ashx"; private static String convertStreamToUTF8String(InputStream stream) throws IOException { String result = ""; StringBuilder sb = new StringBuilder(); try { InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[4096]; int readedChars = 0; while (readedChars != -1) { readedChars = reader.read(buffer); if (readedChars > 0) sb.append(buffer, 0, readedChars); } result = sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } private static String load(String contents) throws IOException { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(60000); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream()); w.write(contents); w.flush(); InputStream istream = conn.getInputStream(); String result = convertStreamToUTF8String(istream); android.util.Log.d("REST", "REST result\n" + result); return result; } catch(Exception e) { android.util.Log.d("REST", "REST exception\n" + e.getMessage()); e.printStackTrace(); throw e; } } private static Object mapObject(Object o) { Object finalValue = null; if (o.getClass() == String.class) { finalValue = o; } else if (Number.class.isInstance(o)) { finalValue = String.valueOf(o); } else if (Date.class.isInstance(o)) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA")); finalValue = sdf.format((Date)o); } else if (Collection.class.isInstance(o)) { Collection<?> col = (Collection<?>) o; JSONArray jarray = new JSONArray(); for (Object item : col) { jarray.put(mapObject(item)); } finalValue = jarray; } else { Map<String, Object> map = new HashMap<String, Object>(); Method[] methods = o.getClass().getMethods(); for (Method method : methods) { if (method.getDeclaringClass() == o.getClass() && method.getModifiers() == Modifier.PUBLIC && method.getName().startsWith("get")) { String key = method.getName().substring(3); try { Object obj = method.invoke(o, null); Object value = mapObject(obj); map.put(key, value); finalValue = new JSONObject(map); } catch (Exception e) { e.printStackTrace(); } } } } return finalValue; } // public static JSONObject CreateNewAccount(String userName, String fullName, String email, String title, String gender, String country, String password) throws Exception { // JSONObject parameters = new JSONObject(); // parameters.put("userName", mapObject(userName)); // parameters.put("fullName", mapObject(fullName)); // parameters.put("email", mapObject(email)); // parameters.put("title", mapObject(title)); // parameters.put("gender", mapObject(gender)); // parameters.put("country", mapObject(country)); // parameters.put("password", mapObject(password)); // // JSONObject o = new JSONObject(); // o.put("interface","RestAPI"); // o.put("method", "CreateNewAccount"); // o.put("parameters", parameters); // // return new JSONObject(load(o.toString())); // } // // public static JSONObject GetUserDetails(String userName) throws Exception { // JSONObject parameters = new JSONObject(); // parameters.put("userName", mapObject(userName)); // // JSONObject o = new JSONObject(); // o.put("interface","RestAPI"); // o.put("method", "GetUserDetails"); // o.put("parameters", parameters); // // return new JSONObject(load(o.toString())); // } // // public static JSONObject UserAuthentication(String userName,String password) throws Exception { // JSONObject parameters = new JSONObject(); // parameters.put("userName", mapObject(userName)); // parameters.put("password", mapObject(password)); // // JSONObject o = new JSONObject(); // o.put("interface","RestAPI"); // o.put("method", "UserAuthentication"); // o.put("parameters", parameters); // // return new JSONObject(load(o.toString())); // } public static JSONObject getEvents() throws Exception { JSONObject parameters = new JSONObject(); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "getEvents"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject getSignupOption() throws Exception { JSONObject parameters = new JSONObject(); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "getSignupOption"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject signup(String Email, String Username, String TitleId, String FullName, String GenderId, String Instituition, String Faculty, String Department, String ResearchField, String Address, String State, String PostalCode, String CountryId, String PhoneNumber, String FaxNumber, String encryptedPassword) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("Email", Email); parameters.put("Username", Username); parameters.put("TitleId", TitleId); parameters.put("FullName", FullName); parameters.put("GenderId", GenderId); parameters.put("Instituition", Instituition); parameters.put("Faculty", Faculty); parameters.put("Department", Department); parameters.put("ResearchField", ResearchField); parameters.put("Address", Address); parameters.put("State", State); parameters.put("PostalCode", PostalCode); parameters.put("CountryId", CountryId); parameters.put("PhoneNumber", PhoneNumber); parameters.put("FaxNumber", FaxNumber); parameters.put("encryptedPassword", encryptedPassword); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "signup"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject login(String Username, String encryptedPassword) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("Username", Username); parameters.put("encryptedPassword", encryptedPassword); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "login"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject changeUserDetail(String UserId, String Email, String Username, String TitleId, String FullName, String GenderId, String Instituition, String Faculty, String Department, String ResearchField, String Address, String State, String PostalCode, String CountryId, String PhoneNumber, String FaxNumber, String encryptedPassword) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("UserId", UserId); parameters.put("Email", Email); parameters.put("Username", Username); parameters.put("TitleId", TitleId); parameters.put("FullName", FullName); parameters.put("GenderId", GenderId); parameters.put("Instituition", Instituition); parameters.put("Faculty", Faculty); parameters.put("Department", Department); parameters.put("ResearchField", ResearchField); parameters.put("Address", Address); parameters.put("State", State); parameters.put("PostalCode", PostalCode); parameters.put("CountryId", CountryId); parameters.put("PhoneNumber", PhoneNumber); parameters.put("FaxNumber", FaxNumber); parameters.put("encryptedPassword", encryptedPassword); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "changeUserDetail"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject getUserDetail(String UserId) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("UserId", UserId); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "getUserDetail"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject getRegisterEventOption(String ConferenceId) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("ConferenceId", ConferenceId); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "getRegisterEventOption"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } public static JSONObject registerEvent(String ConferenceId, String FeeId, String UserId, String UserTypeId) throws Exception { JSONObject parameters = new JSONObject(); parameters.put("ConferenceId", ConferenceId); parameters.put("FeeId", FeeId); parameters.put("UserId", UserId); parameters.put("UserTypeId", UserTypeId); JSONObject o = new JSONObject(); o.put("interface","RestAPI"); o.put("method", "registerEvent"); o.put("parameters", parameters); return new JSONObject(load(o.toString())); } }
Markdown
UTF-8
1,143
2.9375
3
[ "MIT" ]
permissive
# Angular Challenge This folder contains code for interactively displaying a data set, created as part of the Angular Challenge. The below questions should be answered regarding your submission! ##### What is the purpose of your website (what are you trying to convey with your data)? What API does your application fetch information from? ##### > I was trying to show in effective way how many people cross the bridge at fremont at certain times and when there is a big difference in crossing times it cam from the fremont bridge counter. ##### Did you receive help from any other sources (classmates, etc)? If so, please list who (be specific!). ##### > googleing and stackoverflow articles ##### Approximately how many hours did it take you to complete this assignment? ##### > 4 ##### On a scale of 1 (too easy) to 10 (too challenging), how difficult was this assignment? ##### > 7 ##### Did you encounter any problems in this assignment we should warn students about in the future? How can we make the assignment better? ##### > none some API's where very hard to access so maybe in the future warn students more about this.
Java
UTF-8
430
1.726563
2
[]
no_license
package com.ptit.tranhoangminh.newsharefood.views.CategoryViews.activities; import com.ptit.tranhoangminh.newsharefood.models.Category; import java.util.ArrayList; /** * Created by Lãng on 26/4/2018. */ public interface CategoryView { public void showProgress(); public void hideProgress(); public void displayMessage(String message); public void displayCategories(ArrayList<Category> categoriesList); }
C#
UTF-8
6,918
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using SourceDemoParser.Engine; namespace SourceDemoParser { [DebuggerDisplay("{CurrentByte,nq}")] public class SourceBufferWriter { public byte[] Data => _data.ToArray(); public int CurrentBit => _currentBit; public int CurrentByte => _currentBit / 8; private readonly List<byte> _data; private int _currentBit; public SourceBufferWriter() { _data = new List<byte>(); } public SourceBufferWriter(IEnumerable<byte> data) : this() { _data.AddRange(data); } public void WriteBits(int value, int count) { WriteUBits((uint)value, count - 1); WriteUBits((value < 0) ? 1u : 0u, 1); } public void WriteUBits(uint value, int count) { var currentByte = _currentBit / 8; var bitOffset = _currentBit - (currentByte * 8); var bitsToWriteToCurrentByte = 8 - bitOffset; if (bitsToWriteToCurrentByte > count) bitsToWriteToCurrentByte = count; var bytesToAdd = 0; if (count > bitsToWriteToCurrentByte) { var temp = count - bitsToWriteToCurrentByte; bytesToAdd = temp / 8; if ((temp % 8) != 0) ++bytesToAdd; } if (bitOffset == 0) ++bytesToAdd; for (var i = 0; i < bytesToAdd; i++) _data.Add(new byte()); var nBitsWritten = 0; var b = (byte)(value & ((1 << bitsToWriteToCurrentByte) - 1)); b <<= bitOffset; b += _data[currentByte]; _data[currentByte] = b; nBitsWritten += bitsToWriteToCurrentByte; ++currentByte; while (nBitsWritten < count) { bitsToWriteToCurrentByte = count - nBitsWritten; if (bitsToWriteToCurrentByte > 8) bitsToWriteToCurrentByte = 8; b = (byte)((value >> nBitsWritten) & ((1 << bitsToWriteToCurrentByte) - 1)); _data[currentByte] = b; nBitsWritten += bitsToWriteToCurrentByte; ++currentByte; } _currentBit += count; } public void WriteOneBit(int value) { WriteBits(value, 1); } public void WriteOneUBit(uint value) { WriteUBits(value, 1); } public void WriteBoolean(bool value) { var currentByte = _currentBit / 8; if (currentByte > _data.Count - 1) _data.Add(new byte()); if (value) _data[currentByte] += (byte)(1 << _currentBit % 8); ++_currentBit; } public void WriteByte(byte value) { WriteUBits(value, 8); } public void WriteSByte(sbyte value) { WriteBits(value, 8); } public void WriteBytes(Span<byte> values) { foreach (var value in values) WriteByte(value); } public void WriteInt16(short value) { WriteBits(value, 16); } public void WriteUInt16(ushort value) { WriteUBits(value, 16); } public void WriteInt32(int value) { WriteBits(value, 32); } public void WriteUInt32(uint value) { WriteUBits(value, 32); } public void WriteString(ReadOnlySpan<char> value, bool withNullTerminator = true) { foreach (char letter in value) WriteByte((byte)letter); if (withNullTerminator) WriteByte(0); } public void WriteString(ReadOnlySpan<char> value, int size) { WriteString(value, false); for (var i = 0; i < size - value.Length; i++) WriteByte(0); } public void WriteStringField(ReadOnlySpan<char> value) { WriteInt32(value.Length); WriteString(value); } public void WriteBufferield(Span<byte> value) { WriteInt32(value.Length); WriteBytes(value); } public void WriteSingle(float value) { throw new System.NotImplementedException(); } public void WriteBitCoord(float value) { throw new System.NotImplementedException(); } public void WriteVectorBitCoord(Vector value) { throw new System.NotImplementedException(); } public void Write<T>(T value) { if (value is int iVal) WriteInt32(iVal); if (value is float fVal) WriteSingle(fVal); if (value is byte bVal) WriteByte(bVal); if (value is short sVal) WriteInt16(sVal); if (value is Vector vec) { WriteSingle(vec.X); WriteSingle(vec.Y); WriteSingle(vec.Z); } if (value is QAngle ang) { WriteSingle(ang.X); WriteSingle(ang.Y); WriteSingle(ang.Z); } if (value is string str) { WriteString(str.AsSpan()); } else throw new Exception("Type not supported."); } public void WriteBits<T>(T value, int bits) where T : struct { if (value is int i) WriteBits(i, bits); else throw new Exception("Type not supported."); } public void WriteField<T>(Nullable<T> value, Action fieldSetCallback = null) where T : struct { if (value.HasValue) { WriteOneUBit(1); Write<T>(value.Value); if (fieldSetCallback != null) fieldSetCallback.Invoke(); } else { WriteOneUBit(0); } } public void WriteBitField<T>(Nullable<T> value, int bits, Action fieldSetCallback = null) where T : struct { if (value.HasValue) { WriteOneUBit(1); if (value is int iVal) WriteBits(iVal, bits); else throw new Exception("Type not supported."); if (fieldSetCallback != null) fieldSetCallback.Invoke(); } else { WriteOneUBit(0); } } } }
Python
UTF-8
289
4.59375
5
[]
no_license
# Write a program that reads a number in miles, converts it to kilometres, and displays the result. # One mile is 1.60934 kilometres. Display your answer correct to 3 decimal places. Miles = int(input("Enter distance in miles: ")) Kilometres = Miles * 1.60934 print(round(Kilometres, 3))
Java
UTF-8
3,312
1.617188
2
[]
no_license
package com.tencent.biz; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.tencent.mobileqq.hotpatch.NotVerifyClass; import java.util.List; public class PoiMapActivity$SearchResultAdapter extends BaseAdapter { protected LayoutInflater a; public PoiMapActivity$SearchResultAdapter(PoiMapActivity paramPoiMapActivity, Context paramContext) { boolean bool = NotVerifyClass.DO_VERIFY_CLASS; this.jdField_a_of_type_AndroidViewLayoutInflater = LayoutInflater.from(paramContext); } public int getCount() { if (this.jdField_a_of_type_ComTencentBizPoiMapActivity.a == null) { return 0; } if (this.jdField_a_of_type_ComTencentBizPoiMapActivity.e) { return this.jdField_a_of_type_ComTencentBizPoiMapActivity.a.size() + 1; } return this.jdField_a_of_type_ComTencentBizPoiMapActivity.a.size(); } public Object getItem(int paramInt) { if (this.jdField_a_of_type_ComTencentBizPoiMapActivity.a == null) { return null; } return this.jdField_a_of_type_ComTencentBizPoiMapActivity.a.get(paramInt); } public long getItemId(int paramInt) { return 0L; } public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) { if (paramView == null) { paramViewGroup = new PoiMapActivity.PoiItemViewHolder(this.jdField_a_of_type_ComTencentBizPoiMapActivity); paramView = LayoutInflater.from(this.jdField_a_of_type_ComTencentBizPoiMapActivity).inflate(2130903725, null); paramViewGroup.jdField_a_of_type_AndroidWidgetTextView = ((TextView)paramView.findViewById(2131299857)); paramViewGroup.jdField_b_of_type_AndroidWidgetTextView = ((TextView)paramView.findViewById(2131299861)); paramViewGroup.c = paramView.findViewById(2131299862); paramViewGroup.c.setVisibility(4); paramViewGroup.d = paramView.findViewById(2131299863); paramViewGroup.jdField_a_of_type_AndroidViewView = paramView.findViewById(2131299854); paramViewGroup.jdField_b_of_type_AndroidViewView = paramView.findViewById(2131299855); paramView.setTag(paramViewGroup); paramViewGroup.jdField_b_of_type_AndroidViewView.setVisibility(8); if (paramInt != this.jdField_a_of_type_ComTencentBizPoiMapActivity.a.size()) { break label164; } paramViewGroup.d.setVisibility(0); paramViewGroup.jdField_a_of_type_AndroidViewView.setVisibility(8); } label164: PoiMapActivity.POI localPOI; do { return paramView; paramViewGroup = (PoiMapActivity.PoiItemViewHolder)paramView.getTag(); break; paramViewGroup.d.setVisibility(8); paramViewGroup.jdField_a_of_type_AndroidViewView.setVisibility(0); localPOI = (PoiMapActivity.POI)getItem(paramInt); } while (localPOI == null); paramViewGroup.jdField_a_of_type_AndroidWidgetTextView.setText(localPOI.a); paramViewGroup.jdField_b_of_type_AndroidWidgetTextView.setText(localPOI.b); return paramView; } } /* Location: E:\apk\QQ_91\classes5-dex2jar.jar!\com\tencent\biz\PoiMapActivity$SearchResultAdapter.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
C++
UTF-8
739
3.96875
4
[]
no_license
//////////////////////////////////////////////////// // Function name : Max() // Description : find largest number from three numbers. // Input : 10 20 30 // Output : 30 // Author : Shiaji das // Date : 19 june 2021 /////////////////////////////////////////////////// #include<iostream> using namespace std; template<class T> T Max(T no1,T no2,T no3) { if((no1>no2)&&(no1>no3)) { return no1; } else if((no2>no1)&&(no2>no3)) { return no2; } else { return no3; } } int main() { int iRet=0; float fRet=0; iRet=Max(10,20,30); printf("The Maximum number is %d \n",iRet); fRet=Max(5.0,10.0,20.0); printf("The Maximum number is %f \n",fRet); return 0; }
Go
UTF-8
295
2.515625
3
[]
no_license
package events import ( "github.com/artheus/go-events/internal" "github.com/artheus/go-events/types" "time" ) // Create a new event type with provided timestamp and // event object to provide to subscribers func Event(t time.Time, o interface{}) types.Event { return internal.Event(t, o) }
Swift
UTF-8
2,424
3.203125
3
[]
no_license
// // Extensions.swift // GetUp // // Created by Omer Elimelech on 6/22/16. // Copyright © 2108 Omer Elimelech All rights reserved. // import UIKit extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any { public func allKeys() -> [String] { var tempArrayKeys = [String]() for (key, _) in self { tempArrayKeys.append(key as! String) } return tempArrayKeys } } private protocol Mergable { func mergeWithSame<T>(right: T) -> T? } extension Array: Mergable { func mergeWithSame<T>(right: T) -> T? { if let right = right as? Array { return (self + right) as? T } assert(false) return nil } } extension Dictionary: Mergable { func mergeWithSame<T>(right: T) -> T? { if let right = right as? Dictionary { return self.merge(right: right) as? T } assert(false) return nil } } extension Set: Mergable { func mergeWithSame<T>(right: T) -> T? { if let right = right as? Set { return self.union(right) as? T } assert(false) return nil } } public extension Dictionary { func merge(right:Dictionary) -> Dictionary { var merged = self for (k, rv) in right { // case of existing left value if let lv = self[k] { if let lv = lv as? Mergable, type(of: lv) == type(of: rv) { let m = lv.mergeWithSame(right: rv) merged[k] = m } // // else if lv is Mergable { // assert(false, "Expected common type for matching keys!") // } // // else if !(lv is Mergable), let _ = lv as? NSArray { // assert(false, "Dictionary literals use incompatible Foundation Types") // } // // else if !(lv is Mergable), let _ = lv as? NSDictionary { // assert(false, "Dictionary literals use incompatible Foundation Types") // } else { merged[k] = rv } } else { merged[k] = rv } } return merged } }
Markdown
UTF-8
5,360
3.203125
3
[ "Apache-2.0" ]
permissive
# TaskQ: A distributed task queue in Go This is a simple distributed task queue using which you can: * enqueue a task into a named queue. * dequeue a task from a named queue. * acknowledge a task in a named queue. Tasks are either in "active" or "dequeued" state. TaskQ dequeue tasks from the list of active tasks, return them to the user, and put them in the dequeued list. If a dequeued task is not acknowledged after a timetout (2-3 min), the task will be put back in the active queue. ## Installation **Option 1.** Install TaskQ using [goget](https://github.com/soheilhy/goget): ```bash curl -sL https://git.io/goget | bash -s -- github.com/kandoo/beehive/examples/taskq ``` **Option 2.** Install Go 1.4+ on your machine, setup your Go workspace (i.e., the `$GOPATH`), and go get TaskQ: ```bash go get github.com/kandoo/beehive/examples/taskq ``` ## Standalone Mode To run TaskQ in standalone mode with no replication, run the following command: ```bash taskq -logtostderr -taskq.repl=1 ``` This command runs a TaskQ server with a *replication factor* of 1, which basically means saving data on the local machine with no replication on any other nodes. You can send requests to TaskQ either using HTTP or its own text-based protocol. By default, HTTP is served on localhost:7677, TaskQ protocol is served on port 7979, and TaskQ's data is saved in `/tmp/beehive`. You can override these addresses using `-addr`, `-taskq.addr`, and `-statepath`: ```bash taskq -logtostderr -addr=ADDR -taskq.addr=TADDR -statepath=DIR -taskq.repl=1 ``` ## Clustered Mode ### Run the first node Each TaskQ server has two listening ports. One used for its HTTP API and also for Beehive's RPC. The other one is used for TaskQ's text-based protocol. The former is set using `-addr` and the later is set using `-taskq.addr`. You can run the first node using: ```bash taskq -logtostderr -addr ADDR1 -taskq.addr TADDR1 -statepath DIR1 ``` `ADDR1` and `TADDR1` are the listening addresses of the first node in the form of `IP:PORT`. `STATE1` is the directory where the first node stores its state. ### Add a new nodes to the cluster You can add new nodes to the cluster using: ```bash taskq -logtostderr -addr ADDRN -paddrs ADDR1 -taskq.addr TADDRN -statepath DIRN ``` `ADDRN` and `TADDRN` are the listening addresses of the new node in the form of `IP:PORT`. `ADDR1` is the address of the first node. You can also use the address of any other live nodes instead of `ADDR1`. `DIRN` is the directory where the N'th node stores its state. ## API TaskQ has two endpoints: (i) HTTP and (ii) its own text-based protocol. They support the same set of functionalities, but HTTP is easier to use while TaskQ protocol is more efficient. ## HTTP API TaskQ handles HTTP requests in the following format: |URL |Method|Description| |-------------------------|------|-----------| |`/apps/taskq/QUEUE/tasks`|`POST`|Enqueue a task in QUEUE. Task body is submitted as POST data.| |`/apps/taskq/QUEUE/tasks/deque`|`POST`|Dequeue a task from QUEUE. It returns the JSON representation of the dequeued task.| |`/apps/taskq/QUEUE/tasks/ID`|`DELETE`|Acknowledge task ID in QUEUE| For example, you can enqueue a task in TaskQ using the following command: ``` curl -X POST -d "TASKBODY" http://localhost:7677/apps/taskq/queue1/tasks ``` You can dequeue a task using the following command: ``` curl -X POST http://localhost:7677/apps/taskq/queue1/tasks/deque ``` You can acknowlege a dequeued task using the following command: ``` curl -X DELETE http://localhost:7677/apps/taskq/queue1/tasks/1 ``` **NOTE:** You can send HTTP requests to any TaskQ server in your cluster. TaskQ would remain consistent no matter where you initiate your request. ## TaskQ Protocol To avoid the overheads of HTTP, TaskQ also has a text-based protocol with the following requests: |Request|Description| |-------|-----------| |`RID enq QUEUE LEN BODY`|Enqueue a task in QUEUE. LEN is a length of BODY.<sup>+</sup>| |`RID deq QUEUE`|Dequeue a task from QUEUE| |`RID ack QUEUE TASKID`|Acknowledge TASKID in QUEUE| <sup>+</sup> If LEN is 0, the length of the task's body will be calculated automatically. RID is the request ID assigned by the client. This ID is returned along with the response to identify its respective request. TaskQ protocol has the following response format: |Request|Description| |-------|-----------| |`RID enqed QUEUE TASKID`|The task is successfully enqueued.| |`RID deqed QUEUE TASKID LEN BODY`|A task is successfully dequeued.| |`RID acked QUEUE TASKID`|The task is successfully acknowledged.| |`RID error MSG`|There is a request error.| ## Go Client TaskQ has a Go client which is built based on the TaskQ text-based protocol. For more information, refer to [its GoDoc](http://godoc.org/github.com/kandoo/beehive/examples/taskq/client). ## Fault-tolerance TaskQ's replication factor (set via `-taskq.repl`) is the replication factor of one queue. If you have `N` nodes in your cluster and a replication factor of `R` for TaskQ, the nodes that store the tasks of one single queue can be on any `R` nodes. Assuming that `R <= N`, as long as the majority of nodes serving a queue (i.e., `0.5 x R + 1`) are up, TaskQ will serve requests to that queue. Note that, when `R < N`, there will be nodes which does not participate as a replica for a given queue.
C++
WINDOWS-1250
1,932
2.78125
3
[]
no_license
#ifndef PRODUCTO_H #define PRODUCTO_H #define FILE_PRODUCTOS "Archivos/Productos.dat" class Producto { private: int id,codProv,planCta,stock,stockMin; float precioCosto,iva; bool estado; char descripcion[50]; public: void cargarProducto(); ///SETTERS A int setId(int idAux); void setCodProv(int codProv); void setDescripcion(char *descripcion); void setPlanCta(int planCta); void setStock(int stock); void setPrecioCosto(float precioCosto); void setIva(float iva); void setStockMin(int stockMin); void setEstado(bool estado); bool setMod(int id, int tipoOperacion,int cant, float precio); ///SETTERS B int setId(); void setCodProv(); void setDescripcion(); void setPlanCta(); void setStock(); void setPrecioCosto(); void setIva(); void setStockMin(); void setEstado(); void setProducto(Producto target); ///DEVUELVEN: int getId(); int getCodProv(); char* getDescripcion(); int getPlanCta(); int getStock(); float getPrecioCosto(); float getIva(); int getStockMin(); bool getEstado(); Producto getProducto(int idProd);/// Devuelve un producto producto recibiendo su id como parametro. int checkStock(int id, int cant);///verificar cantidad en existencia bool grabarEnDisco();///GRABA EN UN ARCHIVO UN REGISTRO DE TIPO PRODUCTO **HECHA** bool leerDeDisco(int posicion);///Lee de disco un producto cuya posicion se pasa como parmetro **HECHA void mostrarProducto();///muestra un producto int buscarProdxId(int idAux);///DEVUELVE LA POSICION DE UN PRODUCTO POR ID QUE ES PASADO COMO PARAMETRO **HECHA void Modificar_en_disco(int , int, float); }; #endif // PRODUCTO_H
C#
UTF-8
677
3.03125
3
[]
no_license
/* * // Make the action take over the text of the button // When the button is pushed, deduct the necessary resources if available // Create a new text window that updates periodically w/ how long it is // Have update reduce time remaining on new action pane 1x per second // Goal: Have a button that you push, creates another text box which shows how long until completion and the resources gained and modifies resources of the player cost/outcome // Each action can only be active one at a time. Set up a button on the left which becomes inactive once you click it. Then, it ticks down on the right side of the screen. On resolution, player gets that many resources. */
C#
UTF-8
1,887
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { const int maxInt = 255; public float smoothing = 1; public float restTime = 1; public float restTimer = 0; [HideInInspector] public Vector2 targetPos = new Vector2(1, 1); //player在每一关的起点 private Rigidbody2D rigidbody2D; private BoxCollider2D collider2D; void Start() { rigidbody2D = GetComponent<Rigidbody2D>(); collider2D = GetComponent<BoxCollider2D>(); } void Update() { rigidbody2D.MovePosition(Vector2.Lerp(transform.position, targetPos, smoothing * Time.deltaTime)); restTimer += Time.deltaTime; if (restTimer < restTime) return; float h = Input.GetAxisRaw("Horizontal"); float v = Input.GetAxisRaw("Vertical"); RaycastHit2D hitHorizontal, hitVertical; //两个方向的都要检测,会往距离更近的吸,如果距离相同,就往起始方向吸 if (h > 0) { collider2D.enabled = false; hitHorizontal = Physics2D.Linecast(targetPos, targetPos + new Vector2(maxInt, 0)); collider2D.enabled = true; } else if(h < 0) { collider2D.enabled = false; hitHorizontal = Physics2D.Linecast(targetPos, targetPos + new Vector2(-maxInt, 0)); collider2D.enabled = true; } if(v > 0) { collider2D.enabled = false; hitVertical = Physics2D.Linecast(targetPos, targetPos + new Vector2(0, maxInt)); collider2D.enabled = true; } else if(v < 0) { collider2D.enabled = false; hitVertical = Physics2D.Linecast(targetPos, targetPos + new Vector2(0, -maxInt)); collider2D.enabled = true; } } }
Python
UTF-8
3,417
2.84375
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- """ list.py """ import json import optparse import os import sys def main(): parser = optparse.OptionParser() parser.add_option("-d", "--delete", action="store") parser.add_option("-D", "--delete_both", action="store_true") options, args = parser.parse_args() if len(args) == 0: sys.exit(0) filename = args[0] search = None if len(args) == 2: search = args[1].decode("utf-8") delete_recorded = False delete_encoded = False if search and options.delete_both: delete_recorded = True delete_encoded = True if search and options.delete == 'r': delete_recorded = True if search and options.delete == 'e': delete_encoded = True if delete_recorded or delete_encoded: delete_files(filename, search, delete_recorded, delete_encoded) else: list_files(filename, search) def filter_files(filename, search): fp = open(filename, 'r') js = json.load(fp) fp.close() data = js if search: data = filter( lambda item: ( item['title'].find(search) >= 0 or item['fullTitle'].find(search) >= 0 or item['recorded'].find(search) >= 0), js) return data def delete_files(filename, search, delete_recorded, delete_encoded): data = filter_files(filename, search) total_count = 0 total_size = 0 for item in data: print("title: %s" % (item['fullTitle'])) if delete_recorded: p = item['recorded'] sz = get_filesize(p) print("recorded: %s (%s)" % (p, get_pretty_filesize(sz))) if sz: total_count += 1 total_size += (sz or 0) if delete_encoded: p = item['encoded'] sz = get_filesize(p) print("encoded: %s (%s)" % (p, get_pretty_filesize(sz))) if sz: total_count += 1 total_size += (sz or 0) print("") sys.stdout.write("delete %d files (total: %s)? (yes/NO) " % (total_count, get_pretty_filesize(total_size))) ans = sys.stdin.readline() if ans.rstrip().lower() != "yes": print("canceled") sys.exit(0) for item in data: if delete_recorded: p = item['recorded'] if os.path.exists(p): print("delete %s" % p) os.remove(p) if delete_encoded: p = item['encoded'] if os.path.exists(p): print("delete %s" % p) os.remove(p) def list_files(filename, search): data = filter_files(filename, search) for item in data: print("title: %s" % (item['fullTitle'])) sz = get_filesize(item['recorded']) print("recorded: %s (%s)" % (item['recorded'], get_pretty_filesize(sz))) sz = get_filesize(item['encoded']) print("encoded: %s (%s)" % (item['encoded'], get_pretty_filesize(sz))) print("") def get_filesize(path): if not os.path.exists(path): return None else: return os.path.getsize(path) def get_pretty_filesize(sz): if not sz: return "deleted" else: return "%d MB" % (sz / (1024 * 1024)) if __name__ == "__main__": main()
Markdown
UTF-8
1,195
3.015625
3
[]
no_license
jQuery Routes ============= **Download:** [Development](https://github.com/syntacticx/routesjs/zipball/master) | [Production (6KB)](https://github.com/syntacticx/routesjs/raw/master/jquery.routes.min.js) **See Also:** [jQuery View](http://viewjs.com/) Rails style routing for jQuery. Enables back button support, deep linking and allows methods to be called by normal links in your application without adding an event handler. Methods that have been specified in your routes will automatically set the URL of the page when called. $.routes({ "/": "PageView#home", "/article/:id": "ArticlesView#article", "/about/(:page_name)": function(params){} }); Clicking: <a href="#/article/5"></a> Will call: ArticlesView.instance().article({id:5}) Calling: ArticlesView.instance().article({id:6}) Will set URL: "#/article/6" jQuery Routes depends on the [jQuery Address](http://www.asual.com/jquery/address/) plugin which is included in the production build. Alternatively, you can use jQuery Routes to emulate the **hashchange** event $.routes(function(new_hash){ //do stuff }); To unregister the handler above: $.routes(false);
C#
UTF-8
9,342
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ZooboxApplication.Data; using ZooboxApplication.Models.Adoptions; namespace ZooboxApplication.Controllers.Adoptions { //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Controlador de páginas Tipos de Adoção. </summary> /// /// <remarks> André Silva, 09/12/2018. </remarks> //////////////////////////////////////////////////////////////////////////////////////////////////// [Authorize] public class AdoptionTypesController : Controller { private readonly ApplicationDbContext _context; public AdoptionTypesController(ApplicationDbContext context) { _context = context; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Página Tipos de Adoção </summary> /// /// <remarks> André Silva, 09/12/2018. </remarks> /// /// <returns> Retorna a view da página Tipos de Adoção, com uma lista das Tipos de Adoção registados na Base de dados. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task<IActionResult> Index() { return View(await _context.AdoptionType.ToListAsync()); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Detalhes de um Tipo de Adoção </summary> /// /// <remarks> André Silva, 09/12/2018. </remarks> /// /// <param name="Id">- Id do Tipo de Adoção</param> /// <returns> Retorna uma view com os detalhes de um Tipo de Adoção, Caso contrário devolve Not Found</returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var adoptionType = await _context.AdoptionType .FirstOrDefaultAsync(m => m.Id == id); if (adoptionType == null) { return NotFound(); } return View(adoptionType); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Detalhes de um Tipo de Adoção </summary> /// /// <remarks> André Silva, 09/12/2018. </remarks> /// /// <returns> Retorna uma view com um formulário de inserção de um Tipo de Adoção</returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public IActionResult Create() { return View(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> POST:Create, endpoint para criar um Tipo de Adoção recebemdo todos os argumentos necessarios. </summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <param name="AdoptionTypeName"> - Nome do Tipo de Adoção </param> /// <returns> Retorna um view com os Detalhes da novo Tipo de Adoção </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,AdoptionTypeName")] AdoptionType adoptionType) { if (ModelState.IsValid) { _context.Add(adoptionType); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(adoptionType); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> GET:Edit, endpoint para procurar a informação e devolve de um Tipo de Adoção para que se possa editar.</summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <returns> Retorna um view com o formulario preenchido para editar. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var adoptionType = await _context.AdoptionType.FindAsync(id); if (adoptionType == null) { return NotFound(); } return View(adoptionType); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> POST:Edit, endpoint que recebe a informação relativa a um Tipo de Adoção e edit esso Tipo de Adoção.</summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <param name="AdoptionTypeName"> - Nome do Tipo de Adoção </param> /// <returns> Retorna uma view com o Tipo de Adoção editado. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,AdoptionTypeName")] AdoptionType adoptionType) { if (id != adoptionType.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(adoptionType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AdoptionTypeExists(adoptionType.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(adoptionType); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> GET:Delete, recebe um id de um Tipo de Adoção e devolve um view com a informação do mesmo e a opção para apagar.</summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <returns> Retorna uma view com o Tipo de Adoção. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var adoptionType = await _context.AdoptionType .FirstOrDefaultAsync(m => m.Id == id); if (adoptionType == null) { return NotFound(); } return View(adoptionType); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Delete, recebe um id de um Tipo de Adoção e apaga esso Tipo de Adoção.</summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <returns> Retorna o index dos Tipos de Adoção. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var adoptionType = await _context.AdoptionType.FindAsync(id); _context.AdoptionType.Remove(adoptionType); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Verifica se um Tipo de Adoção existe.</summary> /// /// <remarks> Tiago Alves, 10/01/2019. </remarks> /// <param name="Id"> - id do Tipo de Adoção </param> /// <returns> Retorna true ou false </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// private bool AdoptionTypeExists(int id) { return _context.AdoptionType.Any(e => e.Id == id); } } }
Java
UTF-8
168
1.75
2
[]
no_license
package com.wissen.com.wissen.model; public interface Message { public String getPipelineNo(); public String getCompany(); public Integer getSeqence(); }
C++
UTF-8
1,419
2.625
3
[]
no_license
#include "plotData.h" plotData::plotData(const char *fifoname,unsigned int size){ path="/home/suntao/workspace/gorobots/controllers/stbot/genesis/study-tool/fifo"; path += fifoname; pathname =path.c_str(); char temp[100]="/home/suntao/workspace/gorobots/controllers/stbot/genesis/study-tool/studyPlot "; strcat(temp,fifoname); strcat(temp, " "); std::string temp1= std::to_string(size); strcat(temp,temp1.c_str()); plotapp = temp; if((pid = fork())<0){ perror("fork fail!"); std::cout<<"fork fail!"<<std::endl; exit(1); }else if(pid ==0){ childpid = getpid(); std::cout<<"this is child process: "<<childpid<<std::endl; std::cout<<"plotapp is : "<<plotapp<<std::endl; execl("/bin/sh", "sh", "-c", plotapp, (char*)0); exit(127); }else{ parentpid = getpid(); std::cout<<"this is parent process: "<<parentpid<<std::endl; std::cout<<"fifo pathname is : "<<pathname<<std::endl; buf.resize(size); fifo = new ipcFifo(pathname); std::cout<<" create fifo ok"<<std::endl; fifo->openFifo(O_WRONLY); std::cout<<"open fifo ok"<<std::endl; } } plotData::~plotData(){ delete fifo; } void plotData::setData(std::vector<double> data){ for(unsigned int i=0;i<data.size();i++) buf.at(i) = data.at(i); } void plotData::update(){ if(parentpid ==getpid()){ fifo->setSendData(buf); fifo->send(); } } void plotData::plot(std::vector<double> data){ setData(data); update(); }
C
UTF-8
610
3.125
3
[]
no_license
#include <stdio.h> #include "libs/bitmap.h" int main(int argc, char **argv) { bmpImage* img = newBmpImage(10, 10); img->data[0][0] = (pixel) {255, 0, 0}; img->data[0][1] = (pixel) {0, 255, 0}; img->data[0][2] = (pixel) {0, 0, 255}; img->data[1][0] = (pixel) {255, 0, 255}; img->data[2][0] = (pixel) {255, 255, 0}; img->data[3][0] = (pixel) {255, 255, 255}; // Write the image back to disk if (saveBmpImage(img, "img.bmp") != 0) { fprintf(stderr, "Could not save output to '%s'!\n", "img.bmp"); freeBmpImage(img); return 1; } return 0; }
Python
UTF-8
4,153
3.09375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
import numpy as np from igraph import Graph, plot from itertools import combinations import matplotlib matplotlib.use('SVG') import sys reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') __author__ = 'Erica-Li' class hash_tag_graph: """ hash tag graph class """ def __init__(self,window_duration=60,verbose=True): """ Initialize the class :return: hash_tag_graph object """ self.t_window = window_duration self.latest_time = 0 self.graph = Graph() self.verbose=verbose def trim(self): """ remove edges outside time window :return: None """ # identify edges outside window min_time = self.latest_time - self.t_window edges_to_trim = self.graph.es.select(time_lt=min_time) if self.verbose: print("Edges to trim: "+str(edges_to_trim)) # remove edges outside of t_window self.graph.delete_edges(edges_to_trim) # identify vertices with 0 degree to delete vertices_to_trim = self.graph.vs.select(_degree=0) if self.verbose: print("Vertices to trim: "+str(vertices_to_trim._name_index)) self.graph.delete_vertices(vertices_to_trim) def add_tweet(self,hash_tag_tuple,epoch_time): """ Adds tweet to hash tag graph and updates graph such that it only contains tweets withing window_duration of the latest in time tweet. If tweet is outside of the window_duration than it is not added to the graph and nothing happens :return: """ # Check if tweet is in order, inside the window duration, or outside t_diff = self.latest_time - epoch_time > self.t_window if t_diff <= self.t_window: self.latest_time = max(epoch_time,self.latest_time) current_vertices = self.graph.vs._name_index if self.verbose: print('Graph name index: '+str(current_vertices)) print('Graph name index type: '+str(type(current_vertices))) # current vertivces will have none type when it is initilazed empty if current_vertices is not None: # Add hashtag to graph as vertex, if its already exists, nothing happens for hash_tag in hash_tag_tuple: # only add hashtag if it isn't already in the graph if hash_tag not in current_vertices: if self.verbose: print("Adding Vertex: "+str(hash_tag)) self.graph.add_vertex(name=hash_tag) else: # Add hashtag to graph as vertex, if its already exists, nothing happens for hash_tag in hash_tag_tuple: if self.verbose: print("Adding Vertex: "+str(hash_tag)) self.graph.add_vertex(name=hash_tag) # Add edges with associated epoch time for edge in combinations(hash_tag_tuple,r=2): if self.verbose: print('Adding Edge Pair:'+str(edge)+" Time:"+str(epoch_time)) self.graph.add_edge(source=edge[0],target=edge[1],time=epoch_time) self.trim() # if tweet is outside of the time window than toss it else: return return def get_mean_degree(self): """ Compute the average degree :return: np.float, average graph degree """ return np.mean(self.graph.degree()) def draw_graph(self,path): """ Utlity for visualizing the graph. :return: 0 """ print("Drawing HashTag Graph!") layout = self.graph.layout("kk") self.graph.vs["label"] = self.graph.vs["name"] visual_style = {} visual_style["bbox"] = (1600,1600) visual_style["vertex_size"] = 10 visual_style["edge_width"] = 1 visual_style["edge_color"] = 'blue' visual_style["layout"] = layout visual_style["margin"] = 100 graph_plot = plot(self.graph, **visual_style) graph_plot.save(fname=path) return 0
C++
UTF-8
538,830
2.515625
3
[]
no_license
#include "objectscript.h" #include <time.h> using namespace ObjectScript; #define HASH_GROW_SHIFT 0 // ===================================================================== // ===================================================================== // ===================================================================== #if defined __GNUC__ || defined IW_SDK int OS_VSNPRINTF(OS_CHAR * str, size_t size, const OS_CHAR *format, va_list va) { return vsnprintf(str, size, format, va); } #else int OS_VSNPRINTF(OS_CHAR * str, size_t size, const OS_CHAR *format, va_list va) { return vsnprintf_s(str, size, size/sizeof(OS_CHAR), format, va); } #endif int OS_SNPRINTF(OS_CHAR * str, size_t size, const OS_CHAR *format, ...) { va_list va; va_start(va, format); int ret = OS_VSNPRINTF(str, size, format, va); va_end(va); return ret; } static bool OS_ISNAN(float a) { volatile float b = a; return b != b; } static bool OS_ISNAN(double a) { volatile double b = a; return b != b; } #include <float.h> #include <limits.h> template <class T> T OS_getMaxValue(); template <> double OS_getMaxValue<double>(){ return DBL_MAX; } template <> float OS_getMaxValue<float>(){ return FLT_MAX; } template <> int OS_getMaxValue<int>(){ return INT_MAX; } #define OS_MAX_NUMBER OS_getMaxValue<OS_NUMBER>() #define CURRENT_BYTE_ORDER (*(OS_INT32*)"\x01\x02\x03\x04") #define LITTLE_ENDIAN_BYTE_ORDER 0x04030201 #define BIG_ENDIAN_BYTE_ORDER 0x01020304 #define PDP_ENDIAN_BYTE_ORDER 0x02010403 #define IS_LITTLE_ENDIAN (CURRENT_BYTE_ORDER == LITTLE_ENDIAN_BYTE_ORDER) #define IS_BIG_ENDIAN (CURRENT_BYTE_ORDER == BIG_ENDIAN_BYTE_ORDER) #define IS_PDP_ENDIAN (CURRENT_BYTE_ORDER == PDP_ENDIAN_BYTE_ORDER) static inline OS_BYTE toLittleEndianByteOrder(OS_BYTE val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*1); return val; } static inline OS_U16 toLittleEndianByteOrder(OS_U16 val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*2); if(IS_LITTLE_ENDIAN){ return val; } OS_U16 r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[0]; return r; } static inline OS_INT16 toLittleEndianByteOrder(OS_INT16 val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*2); if(IS_LITTLE_ENDIAN){ return val; } OS_INT16 r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[0]; return r; } static inline OS_INT32 toLittleEndianByteOrder(OS_INT32 val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*4); if(IS_LITTLE_ENDIAN){ return val; } OS_INT32 r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[3]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[2]; ((OS_BYTE*)&r)[2] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[3] = ((OS_BYTE*)&val)[0]; return r; } static inline OS_INT64 toLittleEndianByteOrder(OS_INT64 val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*8); if(IS_LITTLE_ENDIAN){ return val; } OS_INT64 r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[7]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[6]; ((OS_BYTE*)&r)[2] = ((OS_BYTE*)&val)[5]; ((OS_BYTE*)&r)[3] = ((OS_BYTE*)&val)[4]; ((OS_BYTE*)&r)[4] = ((OS_BYTE*)&val)[3]; ((OS_BYTE*)&r)[5] = ((OS_BYTE*)&val)[2]; ((OS_BYTE*)&r)[6] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[7] = ((OS_BYTE*)&val)[0]; return r; } static inline float toLittleEndianByteOrder(float val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*4); if(IS_LITTLE_ENDIAN){ return val; } float r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[3]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[2]; ((OS_BYTE*)&r)[2] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[3] = ((OS_BYTE*)&val)[0]; return r; } static inline double toLittleEndianByteOrder(double val) { OS_ASSERT(sizeof(val) == sizeof(OS_BYTE)*8); if(IS_LITTLE_ENDIAN){ return val; } double r; ((OS_BYTE*)&r)[0] = ((OS_BYTE*)&val)[7]; ((OS_BYTE*)&r)[1] = ((OS_BYTE*)&val)[6]; ((OS_BYTE*)&r)[2] = ((OS_BYTE*)&val)[5]; ((OS_BYTE*)&r)[3] = ((OS_BYTE*)&val)[4]; ((OS_BYTE*)&r)[4] = ((OS_BYTE*)&val)[3]; ((OS_BYTE*)&r)[5] = ((OS_BYTE*)&val)[2]; ((OS_BYTE*)&r)[6] = ((OS_BYTE*)&val)[1]; ((OS_BYTE*)&r)[7] = ((OS_BYTE*)&val)[0]; return r; } #define fromLittleEndianByteOrder toLittleEndianByteOrder static const OS_INT32 nan_data = 0x7fc00000; static const float nan_float = fromLittleEndianByteOrder(*(float*)&nan_data); static inline void parseSpaces(const OS_CHAR *& str) { while(*str && OS_IS_SPACE(*str)) str++; } template <class T> static bool parseSimpleHex(const OS_CHAR *& p_str, T& p_val) { T val = 0, prev_val = 0; const OS_CHAR * str = p_str; const OS_CHAR * start = str; for(;; str++){ if(*str >= OS_TEXT('0') && *str <= OS_TEXT('9')){ val = (val << 4) + (T)(*str - OS_TEXT('0')); }else if(*str >= OS_TEXT('a') && *str <= OS_TEXT('f')){ val = (val << 4) + 10 + (T)(*str - OS_TEXT('a')); }else if(*str >= OS_TEXT('A') && *str <= OS_TEXT('F')){ val = (val << 4) + 10 + (T)(*str - OS_TEXT('A')); }else{ break; } if(prev_val > val){ p_str = start; p_val = 0; return false; } prev_val = val; } p_val = val; p_str = str; return str > start; } template <class T> static bool parseSimpleBin(const OS_CHAR *& p_str, T& p_val) { T val = 0, prev_val = 0; const OS_CHAR * str = p_str; const OS_CHAR * start = str; for(; *str >= OS_TEXT('0') && *str <= OS_TEXT('1'); str++){ val = (val << 1) + (T)(*str - OS_TEXT('0')); if(prev_val > val){ p_str = start; p_val = 0; return false; } prev_val = val; } p_val = val; p_str = str; return str > start; } template <class T> static bool parseSimpleOctal(const OS_CHAR *& p_str, T& p_val) { T val = 0, prev_val = 0; const OS_CHAR * str = p_str; const OS_CHAR * start = str; for(; *str >= OS_TEXT('0') && *str <= OS_TEXT('7'); str++) { val = (val << 3) + (T)(*str - OS_TEXT('0')); if(prev_val > val){ p_str = start; p_val = 0; return false; } prev_val = val; } p_val = val; p_str = str; return str > start; } template <class T> static bool parseSimpleDec(const OS_CHAR *& p_str, T& p_val) { T val = 0, prev_val = 0; const OS_CHAR * str = p_str; const OS_CHAR * start = str; for(; *str >= OS_TEXT('0') && *str <= OS_TEXT('9'); str++){ val = val * 10 + (T)(*str - OS_TEXT('0')); if(prev_val > val){ p_str = start; p_val = 0; return false; } prev_val = val; } p_val = val; p_str = str; return str > start; } template <class T> static bool parseSimpleFloat(const OS_CHAR *& p_str, T& p_val) { T val = 0; const OS_CHAR * str = p_str; const OS_CHAR * start = str; for(; *str >= OS_TEXT('0') && *str <= OS_TEXT('9'); str++){ val = val * 10 + (*str - OS_TEXT('0')); } p_val = val; p_str = str; return str > start; } bool OS::Utils::parseFloat(const OS_CHAR *& str, OS_FLOAT& result) { const OS_CHAR * start_str = str; int sign = 1; if(*str == OS_TEXT('-')){ str++; start_str++; sign = -1; }else if(*str == OS_TEXT('+')){ str++; start_str++; } if(str[0] == OS_TEXT('0') && str[1] != OS_TEXT('.')){ bool is_valid, is_octal = false; OS_INT int_val; if(str[1] == OS_TEXT('x') || str[1] == OS_TEXT('X')){ // parse hex str += 2; is_valid = parseSimpleHex(str, int_val); }else if(str[1] == OS_TEXT('b') || str[1] == OS_TEXT('B')){ // parse hex str += 2; is_valid = parseSimpleBin(str, int_val); }else{ // parse octal is_octal = true; is_valid = parseSimpleOctal(str, int_val); } if(!is_valid || (start_str+1 == str && !is_octal)){ result = 0; return false; } if((OS_INT)(OS_FLOAT)int_val != int_val){ result = 0; return false; } result = (OS_FLOAT)int_val; return true; } OS_FLOAT float_val; if(!parseSimpleFloat(str, float_val)){ result = 0; return false; } if(*str == OS_TEXT('.')){ // parse float // parse 1.#INF ... if(sign == 1 && start_str+1 == str && *start_str == OS_TEXT('1') && str[1] == OS_TEXT('#')){ const OS_CHAR * spec[] = {OS_TEXT("INF"), OS_TEXT("IND"), OS_TEXT("QNAN"), NULL}; int i = 0; for(; spec[i]; i++){ if(OS_STRCMP(str, spec[i]) != 0) continue; size_t specLen = OS_STRLEN(spec[i]); str += specLen; if(!*str || OS_IS_SPACE(*str) || OS_STRCHR(OS_TEXT("!@#$%^&*()-+={}[]\\|;:'\",<.>/?`~"), *str)){ OS_INT32 spec_val; switch(i){ case 0: spec_val = 0x7f800000; break; case 1: spec_val = 0xffc00000; break; default: OS_ASSERT(false); // no break case 2: spec_val = 0x7fc00000; break; } result = (OS_FLOAT)fromLittleEndianByteOrder(*(float*)&spec_val); return true; } } result = 0; return false; } OS_FLOAT m = 0.1; for(str++; *str >= OS_TEXT('0') && *str <= OS_TEXT('9'); str++, m *= 0.1){ float_val += (OS_FLOAT)(*str - OS_TEXT('0')) * m; } if(start_str == str){ result = 0; return false; } if(*str == OS_TEXT('e') || *str == OS_TEXT('E')){ str++; bool div = false; // + for default if(*str == OS_TEXT('-')){ div = true; str++; }else if(*str == OS_TEXT('+')){ // div = false; str++; } int pow; if(!parseSimpleDec(str, pow)){ result = 0; return false; } m = 1.0f; for(int i = 0; i < pow; i++){ m *= 10.0f; } if(div){ float_val /= m; }else{ float_val *= m; } } result = sign > 0 ? float_val : -float_val; return true; } if(start_str == str){ result = 0; return false; } result = sign > 0 ? float_val : -float_val; return true; } OS_CHAR * OS::Utils::numToStr(OS_CHAR * dst, OS_INT32 a) { OS_SNPRINTF(dst, sizeof(OS_CHAR)*63, OS_TEXT("%i"), a); return dst; } OS_CHAR * OS::Utils::numToStr(OS_CHAR * dst, OS_INT64 a) { OS_SNPRINTF(dst, sizeof(OS_CHAR)*63, OS_TEXT("%li"), (long int)a); return dst; } OS_CHAR * OS::Utils::numToStr(OS_CHAR * dst, float a, int precision) { return numToStr(dst, (double)a, precision); } OS_CHAR * OS::Utils::numToStr(OS_CHAR * dst, double a, int precision) { OS_CHAR buf[128]; if(precision <= 0) { if(precision < 0) { OS_FLOAT p = 10.0f; for(int i = -precision-1; i > 0; i--){ p *= 10.0f; } a = ::floor(a / p + 0.5f) * p; } OS_SNPRINTF(dst, sizeof(buf)-sizeof(OS_CHAR), OS_TEXT("%.f"), a); return dst; } if(precision == OS_AUTO_PRECISION){ OS_SNPRINTF(dst, sizeof(buf)-sizeof(OS_CHAR), OS_TEXT("%g"), a); return dst; } OS_SNPRINTF(buf, sizeof(buf)-sizeof(OS_CHAR), OS_TEXT("%%.%dg"), precision); int n = OS_SNPRINTF(dst, sizeof(buf)-sizeof(OS_CHAR), buf, a); OS_ASSERT(n >= 1 && !OS_STRSTR(dst, OS_TEXT(".")) || dst[n-1] != '0'); // while(n > 0 && dst[n-1] == '0') dst[--n] = (OS_CHAR)0; // if(n > 0 && dst[n-1] == '.') dst[--n] = (OS_CHAR)0; return dst; } OS_INT OS::Utils::strToInt(const OS_CHAR * str) { return (OS_INT)strToFloat(str); } OS_FLOAT OS::Utils::strToFloat(const OS_CHAR* str) { OS_FLOAT fval; if(parseFloat(str, fval) && (!*str || (*str==OS_TEXT('f') && !str[1]))){ return fval; } return 0; } #define OS_KEY_HASH_START_VALUE 5381 #define OS_ADD_KEY_HASH_VALUE hash = ((hash << 5) + hash) + *buf++ int OS::Utils::keyToHash(const void * buf, int size) { return OS::Utils::addKeyToHash(OS_KEY_HASH_START_VALUE, buf, size); } int OS::Utils::keyToHash(const void * buf1, int size1, const void * buf2, int size2) { int hash = OS::Utils::addKeyToHash(OS_KEY_HASH_START_VALUE, buf1, size1); return OS::Utils::addKeyToHash(hash, buf2, size2); } int OS::Utils::addKeyToHash(int hash, const void * p_buf, int size) { const OS_BYTE * buf = (const OS_BYTE*)p_buf; for(; size >= 8; size -= 8) { OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; OS_ADD_KEY_HASH_VALUE; } switch(size) { case 7: OS_ADD_KEY_HASH_VALUE; case 6: OS_ADD_KEY_HASH_VALUE; case 5: OS_ADD_KEY_HASH_VALUE; case 4: OS_ADD_KEY_HASH_VALUE; case 3: OS_ADD_KEY_HASH_VALUE; case 2: OS_ADD_KEY_HASH_VALUE; case 1: OS_ADD_KEY_HASH_VALUE; } return hash; } int OS::Utils::cmp(const void * buf1, int len1, const void * buf2, int len2) { int len = len1 < len2 ? len1 : len2; int cmp = OS_MEMCMP(buf1, buf2, len); return cmp ? cmp : len1 - len2; } /* int OS::Utils::cmp(const void * buf1, int len1, const void * buf2, int len2, int maxLen) { return cmp(buf1, len1 < maxLen ? len1 : maxLen, buf2, len2 < maxLen ? len2 : maxLen); } */ // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::String::String(OS * os) { string = os->core->newStringValue((void*)NULL, 0); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(GCStringValue * s) { string = s; string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(const String& s) { string = s.string; string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const String& a, const String& b) { string = os->core->newStringValue(a, b); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const OS_CHAR * str) { string = os->core->newStringValue(str); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const OS_CHAR * str, int len) { string = os->core->newStringValue(str, len); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const OS_CHAR * str, int len, const OS_CHAR * str2, int len2) { string = os->core->newStringValue(str, len, str2, len2); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const OS_CHAR * str, int len, bool trim_left, bool trim_right) { string = os->core->newStringValue(str, len, trim_left, trim_right); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const void * buf, int size) { string = os->core->newStringValue(buf, size); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const void * buf1, int size1, const void * buf2, int size2) { string = os->core->newStringValue(buf1, size1, buf2, size2); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, const void * buf1, int size1, const void * buf2, int size2, const void * buf3, int size3) { string = os->core->newStringValue(buf1, size1, buf2, size2, buf3, size3); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, OS_INT value) { string = os->core->newStringValue(value); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::String(OS * os, OS_FLOAT value, int precision) { string = os->core->newStringValue(value, precision); string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } OS::Core::String::~String() { if(string){ // can be cleared by OS::~String OS_ASSERT(string->external_ref_count > 0); string->external_ref_count--; if(string->gc_color == GC_WHITE){ string->gc_color = GC_BLACK; } } } struct OS_VaListDtor { va_list * va; OS_VaListDtor(va_list * p_va){ va = p_va; } ~OS_VaListDtor(){ va_end(*va); } }; OS::Core::String OS::Core::String::format(OS * allocator, int temp_buf_len, const OS_CHAR * fmt, ...) { va_list va; va_start(va, fmt); OS_VaListDtor va_dtor(&va); return String(allocator->core->newStringValueVa(temp_buf_len, fmt, va)); } OS::Core::String OS::Core::String::formatVa(OS * allocator, int temp_buf_len, const OS_CHAR * fmt, va_list va) { return String(allocator->core->newStringValueVa(temp_buf_len, fmt, va)); } OS::Core::String OS::Core::String::format(OS * allocator, const OS_CHAR * fmt, ...) { va_list va; va_start(va, fmt); OS_VaListDtor va_dtor(&va); return String(allocator->core->newStringValueVa(OS_DEF_FMT_BUF_LEN, fmt, va)); } OS::Core::String OS::Core::String::formatVa(OS * allocator, const OS_CHAR * fmt, va_list va) { return String(allocator->core->newStringValueVa(OS_DEF_FMT_BUF_LEN, fmt, va)); } OS::Core::String& OS::Core::String::operator=(const String& b) { if(string != b.string){ OS_ASSERT(string->external_ref_count > 0); string->external_ref_count--; if(string->gc_color == GC_WHITE){ string->gc_color = GC_BLACK; } string = b.string; string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } return *this; } bool OS::Core::String::operator==(const String& b) const { return string == b.string; } bool OS::Core::String::operator==(const OS_CHAR * b) const { return cmp(b) == 0; } bool OS::Core::String::operator==(GCStringValue * b) const { return string == b; } bool OS::Core::String::operator!=(const String& b) const { return string != b.string; } bool OS::Core::String::operator!=(const OS_CHAR * b) const { return cmp(b) != 0; } bool OS::Core::String::operator!=(GCStringValue * b) const { return string != b; } bool OS::Core::String::operator<=(const String& b) const { return cmp(b) <= 0; } bool OS::Core::String::operator<=(const OS_CHAR * b) const { return cmp(b) <= 0; } bool OS::Core::String::operator<(const String& b) const { return cmp(b) < 0; } bool OS::Core::String::operator<(const OS_CHAR * b) const { return cmp(b) < 0; } bool OS::Core::String::operator>=(const String& b) const { return cmp(b) >= 0; } bool OS::Core::String::operator>=(const OS_CHAR * b) const { return cmp(b) >= 0; } bool OS::Core::String::operator>(const String& b) const { return cmp(b) > 0; } bool OS::Core::String::operator>(const OS_CHAR * b) const { return cmp(b) > 0; } int OS::Core::String::cmp(const String& b) const { if(string == b.string){ return 0; } return Utils::cmp(string->toChar(), string->data_size, b.string->toChar(), b.string->data_size); } int OS::Core::String::cmp(const OS_CHAR * b) const { return Utils::cmp(string->toChar(), string->data_size, b, OS_STRLEN(b)); } int OS::Core::String::getHash() const { return string->hash; } OS_NUMBER OS::Core::String::toNumber() const { OS_NUMBER val; if(string->isNumber(&val)){ return val; } return 0; } // ===================================================================== OS::Core::StringBuffer::StringBuffer(OS * p_allocator) { allocator = p_allocator; } OS::Core::StringBuffer::~StringBuffer() { allocator->vectorClear(*this); } OS::Core::StringBuffer& OS::Core::StringBuffer::append(OS_CHAR c) { allocator->vectorAddItem(*this, c OS_DBG_FILEPOS); return *this; } OS::Core::StringBuffer& OS::Core::StringBuffer::append(const OS_CHAR * str) { return append(str, OS_STRLEN(str)); } OS::Core::StringBuffer& OS::Core::StringBuffer::append(const OS_CHAR * str, int len) { allocator->vectorReserveCapacity(*this, count + len OS_DBG_FILEPOS); OS_MEMCPY(buf + count, str, len * sizeof(OS_CHAR)); count += len; return *this; } OS::Core::StringBuffer& OS::Core::StringBuffer::append(const String& str) { return append(str.toChar(), str.getLen()); } OS::Core::StringBuffer& OS::Core::StringBuffer::append(const StringBuffer& buf) { return append(buf.buf, buf.count); } OS::Core::StringBuffer& OS::Core::StringBuffer::operator+=(const String& str) { return append(str); } OS::Core::StringBuffer& OS::Core::StringBuffer::operator+=(const OS_CHAR * str) { return append(str); } OS::Core::StringBuffer::operator OS::Core::String() const { return toString(); } OS::Core::String OS::Core::StringBuffer::toString() const { return String(allocator, buf, count); } OS::Core::GCStringValue * OS::Core::StringBuffer::toGCStringValue() const { return allocator->core->newStringValue(buf, count); } // ===================================================================== OS::String::String(OS * allocator): super(allocator) { this->allocator = allocator->retain(); } OS::String::String(const String& str): super(str) { allocator = str.allocator->retain(); } OS::String::String(OS * allocator, const Core::String& str): super(str) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const OS_CHAR * str): super(allocator, str) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const OS_CHAR * str1, int len1, const OS_CHAR * str2, int len2): super(allocator, str1, len1, str2, len2) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const OS_CHAR * str, int len): super(allocator, str, len) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const OS_CHAR * str, int len, bool trim_left, bool trim_right): super(allocator, str, len, trim_left, trim_right) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const void * buf, int size): super(allocator, buf, size) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, const void * buf1, int size1, const void * buf2, int size2): super(allocator, buf1, size1, buf2, size2) { this->allocator = allocator->retain(); } /* OS::String::String(OS * allocator, const void * buf1, int size1, const void * buf2, int size2, const void * buf3, int size3): super(allocator, buf1, size1, buf2, size2, buf3, size3) { this->allocator = allocator->retain(); } */ OS::String::String(OS * allocator, OS_INT value): super(allocator, value) { this->allocator = allocator->retain(); } OS::String::String(OS * allocator, OS_FLOAT value, int precision): super(allocator, value, precision) { this->allocator = allocator->retain(); } OS::String::~String() { OS_ASSERT(string->external_ref_count > 0); string->external_ref_count--; if(string->gc_color == Core::GC_WHITE){ string->gc_color = Core::GC_BLACK; } string = NULL; allocator->release(); } OS::String& OS::String::operator=(const Core::String& str) { if(string != str.string){ OS_ASSERT(string->external_ref_count > 0); string->external_ref_count--; if(string->gc_color == Core::GC_WHITE){ string->gc_color = Core::GC_BLACK; } string = str.string; string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } return *this; } OS::String& OS::String::operator=(const String& str) { OS_ASSERT(allocator == str.allocator); if(string != str.string){ OS_ASSERT(string->external_ref_count > 0); string->external_ref_count--; if(string->gc_color == Core::GC_WHITE){ string->gc_color = Core::GC_BLACK; } string = str.string; string->external_ref_count++; #ifdef OS_DEBUG this->str = string->toChar(); #endif } return *this; } OS::String& OS::String::operator+=(const String& str) { return *this = allocator->core->newStringValue(*this, str); } OS::String& OS::String::operator+=(const OS_CHAR * str) { return *this = allocator->core->newStringValue(toChar(), getDataSize(), str, OS_STRLEN(str)*sizeof(OS_CHAR)); } OS::String OS::String::operator+(const String& str) const { return String(allocator, allocator->core->newStringValue(*this, str)); } OS::String OS::String::operator+(const OS_CHAR * str) const { return String(allocator, allocator->core->newStringValue(toChar(), getDataSize(), str, OS_STRLEN(str)*sizeof(OS_CHAR))); } OS::String OS::String::trim(bool trim_left, bool trim_right) const { return String(allocator, allocator->core->newStringValue(*this, trim_left, trim_right)); } // ===================================================================== // ===================================================================== // ===================================================================== const OS_CHAR * OS::Core::Tokenizer::getTokenTypeName(TokenType token_type) { switch(token_type){ case NOTHING: return OS_TEXT("NOTHING"); case BEGIN_CODE_BLOCK: return OS_TEXT("BEGIN_CODE_BLOCK"); case END_CODE_BLOCK: return OS_TEXT("END_CODE_BLOCK"); case BEGIN_BRACKET_BLOCK: return OS_TEXT("BEGIN_BRACKET_BLOCK"); case END_BRACKET_BLOCK: return OS_TEXT("END_BRACKET_BLOCK"); case BEGIN_ARRAY_BLOCK: return OS_TEXT("BEGIN_ARRAY_BLOCK"); case END_ARRAY_BLOCK: return OS_TEXT("END_ARRAY_BLOCK"); case CODE_SEPARATOR: return OS_TEXT("CODE_SEPARATOR"); case PARAM_SEPARATOR: return OS_TEXT("PARAM_SEPARATOR"); case COMMENT_LINE: return OS_TEXT("COMMENT_LINE"); case COMMENT_MULTI_LINE: return OS_TEXT("COMMENT_MULTI_LINE"); case NAME: return OS_TEXT("NAME"); // case DOT_NAME: return OS_TEXT("DOT_NAME"); // case IDENTIFER: return OS_TEXT("IDENTIFER"); // case DOT_IDENTIFER: return OS_TEXT("DOT_IDENTIFER"); case STRING: return OS_TEXT("STRING"); case NUMBER: return OS_TEXT("NUMBER"); // case NUM_VECTOR_3: return OS_TEXT("NUM_VECTOR_3"); // case NUM_VECTOR_4: return OS_TEXT("NUM_VECTOR_4"); case OPERATOR: return OS_TEXT("OPERATOR"); case BINARY_OPERATOR: return OS_TEXT("BINARY_OPERATOR"); case OPERATOR_INDIRECT: return OS_TEXT("OPERATOR_INDIRECT"); case OPERATOR_CONCAT: return OS_TEXT("OPERATOR_CONCAT"); case OPERATOR_LOGIC_AND: return OS_TEXT("OPERATOR_LOGIC_AND"); case OPERATOR_LOGIC_OR: return OS_TEXT("OPERATOR_LOGIC_OR"); case OPERATOR_LOGIC_PTR_EQ: return OS_TEXT("OPERATOR_LOGIC_PTR_EQ"); case OPERATOR_LOGIC_PTR_NE: return OS_TEXT("OPERATOR_LOGIC_PTR_NE"); case OPERATOR_LOGIC_EQ: return OS_TEXT("OPERATOR_LOGIC_EQ"); case OPERATOR_LOGIC_NE: return OS_TEXT("OPERATOR_LOGIC_NE"); case OPERATOR_LOGIC_GE: return OS_TEXT("OPERATOR_LOGIC_GE"); case OPERATOR_LOGIC_LE: return OS_TEXT("OPERATOR_LOGIC_LE"); case OPERATOR_LOGIC_GREATER: return OS_TEXT("OPERATOR_LOGIC_GREATER"); case OPERATOR_LOGIC_LESS: return OS_TEXT("OPERATOR_LOGIC_LESS"); case OPERATOR_LOGIC_NOT: return OS_TEXT("OPERATOR_LOGIC_NOT"); case OPERATOR_INC: return OS_TEXT("OPERATOR_INC"); case OPERATOR_DEC: return OS_TEXT("OPERATOR_DEC"); case OPERATOR_QUESTION: return OS_TEXT("OPERATOR_QUESTION"); case OPERATOR_COLON: return OS_TEXT("OPERATOR_COLON"); case OPERATOR_BIT_AND: return OS_TEXT("OPERATOR_BIT_AND"); case OPERATOR_BIT_OR: return OS_TEXT("OPERATOR_BIT_OR"); case OPERATOR_BIT_XOR: return OS_TEXT("OPERATOR_BIT_XOR"); case OPERATOR_BIT_NOT: return OS_TEXT("OPERATOR_BIT_NOT"); case OPERATOR_ADD: return OS_TEXT("OPERATOR_ADD"); case OPERATOR_SUB: return OS_TEXT("OPERATOR_SUB"); case OPERATOR_MUL: return OS_TEXT("OPERATOR_MUL"); case OPERATOR_DIV: return OS_TEXT("OPERATOR_DIV"); case OPERATOR_MOD: return OS_TEXT("OPERATOR_MOD"); case OPERATOR_LSHIFT: return OS_TEXT("OPERATOR_LSHIFT"); case OPERATOR_RSHIFT: return OS_TEXT("OPERATOR_RSHIFT"); case OPERATOR_POW: return OS_TEXT("OPERATOR_POW"); case OPERATOR_BIT_AND_ASSIGN: return OS_TEXT("OPERATOR_BIT_AND_ASSIGN"); case OPERATOR_BIT_OR_ASSIGN: return OS_TEXT("OPERATOR_BIT_OR_ASSIGN"); case OPERATOR_BIT_XOR_ASSIGN: return OS_TEXT("OPERATOR_BIT_XOR_ASSIGN"); case OPERATOR_BIT_NOT_ASSIGN: return OS_TEXT("OPERATOR_BIT_NOT_ASSIGN"); case OPERATOR_ADD_ASSIGN: return OS_TEXT("OPERATOR_ADD_ASSIGN"); case OPERATOR_SUB_ASSIGN: return OS_TEXT("OPERATOR_SUB_ASSIGN"); case OPERATOR_MUL_ASSIGN: return OS_TEXT("OPERATOR_MUL_ASSIGN"); case OPERATOR_DIV_ASSIGN: return OS_TEXT("OPERATOR_DIV_ASSIGN"); case OPERATOR_MOD_ASSIGN: return OS_TEXT("OPERATOR_MOD_ASSIGN"); case OPERATOR_LSHIFT_ASSIGN: return OS_TEXT("OPERATOR_LSHIFT_ASSIGN"); case OPERATOR_RSHIFT_ASSIGN: return OS_TEXT("OPERATOR_RSHIFT_ASSIGN"); case OPERATOR_POW_ASSIGN: return OS_TEXT("OPERATOR_POW_ASSIGN"); case OPERATOR_ASSIGN: return OS_TEXT("OPERATOR_ASSIGN"); case OPERATOR_RESERVED: return OS_TEXT("OPERATOR_RESERVED"); case OPERATOR_END: return OS_TEXT("OPERATOR_END"); // case PRE_PROCESSOR: return OS_TEXT("PRE_PROCESSOR"); case ERROR_TOKEN: return OS_TEXT("ERROR_TOKEN"); } return OS_TEXT("UNKNOWN_TOKENTYPE"); } OS::Core::Tokenizer::TokenData::TokenData(TextData * p_text_data, const String& p_str, TokenType p_type, int p_line, int p_pos): str(p_str) { text_data = p_text_data->retain(); ref_count = 1; type = p_type; line = p_line; pos = p_pos; // vec3 = NULL; } OS * OS::Core::Tokenizer::TokenData::getAllocator() const { return text_data->allocator; } OS::Core::Tokenizer::TokenData::~TokenData() { OS_ASSERT(ref_count == 0); text_data->release(); } OS::Core::Tokenizer::TokenData * OS::Core::Tokenizer::TokenData::retain() { ref_count++; return this; } void OS::Core::Tokenizer::TokenData::release() { if(--ref_count <= 0){ OS_ASSERT(ref_count == 0); OS * allocator = getAllocator(); this->~TokenData(); allocator->free(this); } } OS_FLOAT OS::Core::Tokenizer::TokenData::getFloat() const { return float_value; } bool OS::Core::Tokenizer::TokenData::isTypeOf(TokenType token_type) const { if(type == token_type){ return true; } if(token_type == OS::Core::Tokenizer::SEPARATOR){ switch(type) { case OS::Core::Tokenizer::BEGIN_CODE_BLOCK: // { case OS::Core::Tokenizer::END_CODE_BLOCK: // } case OS::Core::Tokenizer::BEGIN_BRACKET_BLOCK: // ( case OS::Core::Tokenizer::END_BRACKET_BLOCK: // ) case OS::Core::Tokenizer::BEGIN_ARRAY_BLOCK: // [ case OS::Core::Tokenizer::END_ARRAY_BLOCK: // ] case OS::Core::Tokenizer::CODE_SEPARATOR: // ; case OS::Core::Tokenizer::PARAM_SEPARATOR: // , return true; } return false; } if(token_type == BINARY_OPERATOR){ switch(type) { case OS::Core::Tokenizer::PARAM_SEPARATOR: case OS::Core::Tokenizer::OPERATOR_QUESTION: case OS::Core::Tokenizer::OPERATOR_INDIRECT: // . case OS::Core::Tokenizer::OPERATOR_CONCAT: // .. case OS::Core::Tokenizer::OPERATOR_IN: // in case OS::Core::Tokenizer::OPERATOR_ISPROTOTYPEOF: case OS::Core::Tokenizer::OPERATOR_IS: case OS::Core::Tokenizer::OPERATOR_LOGIC_AND: // && case OS::Core::Tokenizer::OPERATOR_LOGIC_OR: // || case OS::Core::Tokenizer::OPERATOR_LOGIC_PTR_EQ: // === case OS::Core::Tokenizer::OPERATOR_LOGIC_PTR_NE: // !== case OS::Core::Tokenizer::OPERATOR_LOGIC_EQ: // == case OS::Core::Tokenizer::OPERATOR_LOGIC_NE: // != case OS::Core::Tokenizer::OPERATOR_LOGIC_GE: // >= case OS::Core::Tokenizer::OPERATOR_LOGIC_LE: // <= case OS::Core::Tokenizer::OPERATOR_LOGIC_GREATER: // > case OS::Core::Tokenizer::OPERATOR_LOGIC_LESS: // < case OS::Core::Tokenizer::OPERATOR_BIT_AND: // & case OS::Core::Tokenizer::OPERATOR_BIT_OR: // | case OS::Core::Tokenizer::OPERATOR_BIT_XOR: // ^ case OS::Core::Tokenizer::OPERATOR_BIT_NOT: // ~ case OS::Core::Tokenizer::OPERATOR_ADD: // + case OS::Core::Tokenizer::OPERATOR_SUB: // - case OS::Core::Tokenizer::OPERATOR_MUL: // * case OS::Core::Tokenizer::OPERATOR_DIV: // / case OS::Core::Tokenizer::OPERATOR_MOD: // % case OS::Core::Tokenizer::OPERATOR_LSHIFT: // << case OS::Core::Tokenizer::OPERATOR_RSHIFT: // >> case OS::Core::Tokenizer::OPERATOR_POW: // ** case OS::Core::Tokenizer::OPERATOR_BIT_AND_ASSIGN: // &= case OS::Core::Tokenizer::OPERATOR_BIT_OR_ASSIGN: // |= case OS::Core::Tokenizer::OPERATOR_BIT_XOR_ASSIGN: // ^= case OS::Core::Tokenizer::OPERATOR_BIT_NOT_ASSIGN: // ~= case OS::Core::Tokenizer::OPERATOR_ADD_ASSIGN: // += case OS::Core::Tokenizer::OPERATOR_SUB_ASSIGN: // -= case OS::Core::Tokenizer::OPERATOR_MUL_ASSIGN: // *= case OS::Core::Tokenizer::OPERATOR_DIV_ASSIGN: // /= case OS::Core::Tokenizer::OPERATOR_MOD_ASSIGN: // %= case OS::Core::Tokenizer::OPERATOR_LSHIFT_ASSIGN: // <<= case OS::Core::Tokenizer::OPERATOR_RSHIFT_ASSIGN: // >>= case OS::Core::Tokenizer::OPERATOR_POW_ASSIGN: // **= case OS::Core::Tokenizer::OPERATOR_ASSIGN: // = return true; } return false; } return false; } bool OS::Core::Tokenizer::operator_initialized = false; OS::Core::Tokenizer::OperatorDesc OS::Core::Tokenizer::operator_desc[] = { { OPERATOR_INDIRECT, OS_TEXT(".") }, { OPERATOR_CONCAT, OS_TEXT("..") }, { REST_ARGUMENTS, OS_TEXT("...") }, { OPERATOR_RESERVED, OS_TEXT("->") }, { OPERATOR_RESERVED, OS_TEXT("::") }, { OPERATOR_LOGIC_AND, OS_TEXT("&&") }, { OPERATOR_LOGIC_OR, OS_TEXT("||") }, { OPERATOR_LOGIC_PTR_EQ, OS_TEXT("===") }, { OPERATOR_LOGIC_PTR_NE, OS_TEXT("!==") }, { OPERATOR_LOGIC_EQ, OS_TEXT("==") }, { OPERATOR_LOGIC_NE, OS_TEXT("!=") }, { OPERATOR_LOGIC_GE, OS_TEXT(">=") }, { OPERATOR_LOGIC_LE, OS_TEXT("<=") }, { OPERATOR_LOGIC_GREATER, OS_TEXT(">") }, { OPERATOR_LOGIC_LESS, OS_TEXT("<") }, { OPERATOR_LOGIC_NOT, OS_TEXT("!") }, { OPERATOR_INC, OS_TEXT("++") }, { OPERATOR_DEC, OS_TEXT("--") }, { OPERATOR_QUESTION, OS_TEXT("?") }, { OPERATOR_COLON, OS_TEXT(":") }, { OPERATOR_LENGTH, OS_TEXT("#") }, { OPERATOR_BIT_AND, OS_TEXT("&") }, { OPERATOR_BIT_OR, OS_TEXT("|") }, { OPERATOR_BIT_XOR, OS_TEXT("^") }, { OPERATOR_BIT_NOT, OS_TEXT("~") }, { OPERATOR_CONCAT, OS_TEXT("..") }, { OPERATOR_ADD, OS_TEXT("+") }, { OPERATOR_SUB, OS_TEXT("-") }, { OPERATOR_MUL, OS_TEXT("*") }, { OPERATOR_DIV, OS_TEXT("/") }, { OPERATOR_MOD, OS_TEXT("%") }, { OPERATOR_LSHIFT, OS_TEXT("<<") }, { OPERATOR_RSHIFT, OS_TEXT(">>") }, { OPERATOR_POW, OS_TEXT("**") }, { OPERATOR_BIT_AND_ASSIGN, OS_TEXT("&=") }, { OPERATOR_BIT_OR_ASSIGN, OS_TEXT("|=") }, { OPERATOR_BIT_XOR_ASSIGN, OS_TEXT("^=") }, { OPERATOR_BIT_NOT_ASSIGN, OS_TEXT("~=") }, { OPERATOR_ADD_ASSIGN, OS_TEXT("+=") }, { OPERATOR_SUB_ASSIGN, OS_TEXT("-=") }, { OPERATOR_MUL_ASSIGN, OS_TEXT("*=") }, { OPERATOR_DIV_ASSIGN, OS_TEXT("/=") }, { OPERATOR_MOD_ASSIGN, OS_TEXT("%=") }, { OPERATOR_LSHIFT_ASSIGN, OS_TEXT("<<=") }, { OPERATOR_RSHIFT_ASSIGN, OS_TEXT(">>=") }, { OPERATOR_POW_ASSIGN, OS_TEXT("**=") }, { OPERATOR_ASSIGN, OS_TEXT("=") }, { BEGIN_CODE_BLOCK, OS_TEXT("{") }, { END_CODE_BLOCK, OS_TEXT("}") }, { BEGIN_BRACKET_BLOCK, OS_TEXT("(") }, { END_BRACKET_BLOCK, OS_TEXT(")") }, { BEGIN_ARRAY_BLOCK, OS_TEXT("[") }, { END_ARRAY_BLOCK, OS_TEXT("]") }, { CODE_SEPARATOR, OS_TEXT(";") }, { PARAM_SEPARATOR, OS_TEXT(",") } }; const int OS::Core::Tokenizer::operator_count = sizeof(operator_desc) / sizeof(operator_desc[0]); int OS::Core::Tokenizer::compareOperatorDesc(const void * a, const void * b) { const OperatorDesc * op0 = (const OperatorDesc*)a; const OperatorDesc * op1 = (const OperatorDesc*)b; return (int)OS_STRLEN(op1->name) - (int)OS_STRLEN(op0->name); } void OS::Core::Tokenizer::initOperatorsTable() { if(!operator_initialized){ ::qsort(operator_desc, operator_count, sizeof(operator_desc[0]), Tokenizer::compareOperatorDesc); operator_initialized = true; } } OS::Core::Tokenizer::TextData::TextData(OS * p_allocator): filename(p_allocator) { allocator = p_allocator; ref_count = 1; } OS::Core::Tokenizer::TextData::~TextData() { OS_ASSERT(!ref_count); } OS::Core::Tokenizer::TextData * OS::Core::Tokenizer::TextData::retain() { ref_count++; return this; } void OS::Core::Tokenizer::TextData::release() { if(--ref_count <= 0){ OS_ASSERT(!ref_count); OS * allocator = this->allocator; allocator->vectorClear(lines); this->~TextData(); allocator->free(this); } } OS::Core::Tokenizer::Tokenizer(OS * p_allocator) { allocator = p_allocator; initOperatorsTable(); settings.save_comments = false; error = ERROR_NOTHING; cur_line = 0; cur_pos = 0; text_data = new (allocator->malloc(sizeof(TextData) OS_DBG_FILEPOS)) TextData(allocator); } OS * OS::Core::Tokenizer::getAllocator() { return allocator; } OS::Core::Tokenizer::~Tokenizer() { OS * allocator = getAllocator(); for(int i = 0; i < tokens.count; i++){ TokenData * token = tokens[i]; token->release(); } allocator->vectorClear(tokens); // allocator->vectorClear(lines); text_data->release(); } OS::Core::Tokenizer::TokenData * OS::Core::Tokenizer::removeToken(int i) { TokenData * token = getToken(i); getAllocator()->vectorRemoveAtIndex(tokens, i); return token; } void OS::Core::Tokenizer::insertToken(int i, TokenData * token OS_DBG_FILEPOS_DECL) { getAllocator()->vectorInsertAtIndex(tokens, i, token OS_DBG_FILEPOS_PARAM); } bool OS::Core::Tokenizer::parseText(const OS_CHAR * text, int len, const String& filename) { OS_ASSERT(text_data->lines.count == 0); OS * allocator = getAllocator(); // text_data->release(); // text_data = new (allocator->malloc(sizeof(TextData))) TextData(allocator); text_data->filename = filename; const OS_CHAR * str = text; const OS_CHAR * str_end = str + len; while(str < str_end) { #if 0 const OS_CHAR * line_end = OS_STRCHR(str, OS_TEXT('\n')); if(line_end){ allocator->vectorAddItem(text_data->lines, String(allocator, str, line_end - str, false, true) OS_DBG_FILEPOS); str = line_end+1; }else{ allocator->vectorAddItem(text_data->lines, String(allocator, str, str_end - str, false, true) OS_DBG_FILEPOS); break; } #else const OS_CHAR * line_end = str; for(; line_end < str_end && *line_end != OS_TEXT('\n'); line_end++); allocator->vectorAddItem(text_data->lines, String(allocator, str, line_end - str, false, true) OS_DBG_FILEPOS); str = line_end+1; #endif } return parseLines(); } void OS::Core::Tokenizer::TokenData::setFloat(OS_FLOAT value) { float_value = value; } OS::Core::Tokenizer::TokenData * OS::Core::Tokenizer::addToken(const String& str, TokenType type, int line, int pos OS_DBG_FILEPOS_DECL) { OS * allocator = getAllocator(); TokenData * token = new (allocator->malloc(sizeof(TokenData) OS_DBG_FILEPOS_PARAM)) TokenData(text_data, str, type, line, pos); allocator->vectorAddItem(tokens, token OS_DBG_FILEPOS); return token; } static bool isValidCharAfterNumber(const OS_CHAR * str) { return !*str || OS_IS_SPACE(*str) || OS_STRCHR(OS_TEXT("!@#$%^&*()-+={}[]\\|;:'\",<.>/?`~"), *str); } bool OS::Core::Tokenizer::parseFloat(const OS_CHAR *& str, OS_FLOAT& fval, bool parse_end_spaces) { if(Utils::parseFloat(str, fval)){ if(isValidCharAfterNumber(str)){ if(parse_end_spaces){ parseSpaces(str); } return true; } if(*str == OS_TEXT('f') && isValidCharAfterNumber(str+1)){ str++; if(parse_end_spaces){ parseSpaces(str); } return true; } } return false; } bool OS::Core::Tokenizer::parseLines() { OS * allocator = getAllocator(); cur_line = cur_pos = 0; for(; cur_line < text_data->lines.count; cur_line++){ // parse line const OS_CHAR * line_start = text_data->lines[cur_line].toChar(); const OS_CHAR * str = line_start; cur_pos = 0; for(;;){ // skip spaces parseSpaces(str); if(!*str){ break; } if(*str == OS_TEXT('"') || *str == OS_TEXT('\'')){ // begin string StringBuffer s(allocator); OS_CHAR closeChar = *str; const OS_CHAR * token_start = str; for(str++; *str && *str != closeChar;){ OS_CHAR c = *str++; if(c == OS_TEXT('\\')){ switch(*str){ case OS_TEXT('r'): c = OS_TEXT('\r'); str++; break; case OS_TEXT('n'): c = OS_TEXT('\n'); str++; break; case OS_TEXT('t'): c = OS_TEXT('\t'); str++; break; case OS_TEXT('\"'): c = OS_TEXT('\"'); str++; break; case OS_TEXT('\''): c = OS_TEXT('\''); str++; break; case OS_TEXT('\\'): c = OS_TEXT('\\'); str++; break; //case OS_TEXT('x'): default: { OS_INT val; int maxVal = sizeof(OS_CHAR) == 2 ? 0xFFFF : 0xFF; if(*str == OS_TEXT('x') || *str == OS_TEXT('X')){ // parse hex str++; if(!parseSimpleHex(str, val)){ cur_pos = str - line_start; error = ERROR_CONST_STRING_ESCAPE_CHAR; return false; } }else if(*str == OS_TEXT('0')){ // octal if(!parseSimpleOctal(str, val)){ cur_pos = str - line_start; error = ERROR_CONST_STRING_ESCAPE_CHAR; return false; } }else if(*str >= OS_TEXT('1') && *str <= OS_TEXT('9')){ if(!parseSimpleDec(str, val)){ cur_pos = str - line_start; error = ERROR_CONST_STRING_ESCAPE_CHAR; return false; } }else{ val = c; } c = (OS_CHAR)(val <= maxVal ? val : maxVal); } break; } } s.append(c); } if(*str != closeChar){ cur_pos = str - line_start; error = ERROR_CONST_STRING; return false; } str++; addToken(s, STRING, cur_line, token_start - line_start OS_DBG_FILEPOS); continue; } if(*str == OS_TEXT('/')){ if(str[1] == OS_TEXT('/')){ // begin line comment if(settings.save_comments){ addToken(String(allocator, str), COMMENT_LINE, cur_line, str - line_start OS_DBG_FILEPOS); } break; } if(str[1] == OS_TEXT('*')){ // begin multi line comment StringBuffer comment(allocator); comment.append(str, 2); int startLine = cur_line; int startPos = str - line_start; for(str += 2;;){ const OS_CHAR * end = OS_STRSTR(str, OS_TEXT("*/")); if(end){ if(settings.save_comments){ comment.append(str, (int)(end+2 - str)); addToken(comment, COMMENT_MULTI_LINE, startLine, startPos OS_DBG_FILEPOS); } str = end + 2; break; } if(cur_line >= text_data->lines.count){ error = ERROR_MULTI_LINE_COMMENT; cur_pos = str - line_start; return false; } if(settings.save_comments){ comment.append(str); comment.append(OS_TEXT("\n")); // OS_TEXT("\r\n")); } str = line_start = text_data->lines[++cur_line].toChar(); } continue; } } if(*str == OS_TEXT('_') || *str == OS_TEXT('$') || *str == OS_TEXT('@') || (*str >= OS_TEXT('a') && *str <= OS_TEXT('z')) || (*str >= OS_TEXT('A') && *str <= OS_TEXT('Z')) ) { // parse name const OS_CHAR * name_start = str; for(str++; *str; str++){ if(*str == OS_TEXT('_') || *str == OS_TEXT('$') || *str == OS_TEXT('@') || (*str >= OS_TEXT('a') && *str <= OS_TEXT('z')) || (*str >= OS_TEXT('A') && *str <= OS_TEXT('Z')) || (*str >= OS_TEXT('0') && *str <= OS_TEXT('9')) ) { continue; } break; } String name = String(allocator, name_start, str - name_start); TokenType type = NAME; addToken(name, type, cur_line, name_start - line_start OS_DBG_FILEPOS); continue; } // parse operator if(0 && (*str == OS_TEXT('-') || *str == OS_TEXT('+')) && (str[1] >= OS_TEXT('0') && str[1] <= OS_TEXT('9'))){ int i = 0; }else{ int i; for(i = 0; i < operator_count; i++){ size_t len = OS_STRLEN(operator_desc[i].name); if(OS_STRNCMP(str, operator_desc[i].name, len) == 0){ addToken(String(allocator, str, (int)len), operator_desc[i].type, cur_line, str - line_start OS_DBG_FILEPOS); str += len; break; } } if(i < operator_count){ continue; } } { OS_FLOAT fval; const OS_CHAR * token_start = str; if(parseFloat(str, fval, true)){ TokenData * token = addToken(String(allocator, token_start, str - token_start, false, true), NUMBER, cur_line, token_start - line_start OS_DBG_FILEPOS); token->setFloat(fval); continue; } } error = ERROR_SYNTAX; cur_pos = str - line_start; return false; } } // PrintTokens(); return true; } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::Compiler::ExpressionList::ExpressionList(OS * p_allocator) { allocator = p_allocator; } OS::Core::Compiler::ExpressionList::~ExpressionList() { allocator->vectorDeleteItems(*this); allocator->vectorClear(*this); } bool OS::Core::Compiler::ExpressionList::isValue() const { return count > 0 && buf[count-1]->isValue(); } bool OS::Core::Compiler::ExpressionList::isClear() const { return count <= 0 || buf[count-1]->isClear(); } bool OS::Core::Compiler::ExpressionList::isWriteable() const { return count > 0 && buf[count-1]->isWriteable(); } OS::Core::Compiler::Expression * OS::Core::Compiler::ExpressionList::add(Expression * exp OS_DBG_FILEPOS_DECL) { allocator->vectorAddItem(*this, exp OS_DBG_FILEPOS_PARAM); return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::ExpressionList::removeIndex(int i) { Expression * exp = (*this)[i]; allocator->vectorRemoveAtIndex(*this, i); return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::ExpressionList::removeLast() { return removeIndex(count-1); } void OS::Core::Compiler::ExpressionList::swap(ExpressionList& list) { OS_ASSERT(allocator == list.allocator); Expression ** save_buf = buf; int save_count = count; int save_capacity = capacity; buf = list.buf; count = list.count; capacity = list.capacity; list.buf = save_buf; list.count = save_count; list.capacity = save_capacity; } // ===================================================================== OS::Core::Compiler::LocalVarDesc::LocalVarDesc() { up_count = 0; up_scope_count = 0; index = 0; type = LOCAL_GENERIC; } OS::Core::Compiler::Expression::Expression(ExpressionType p_type, TokenData * p_token): list(p_token->getAllocator()) { token = p_token->retain(); type = p_type; ret_values = 0; active_locals = 0; } OS::Core::Compiler::Expression::Expression(ExpressionType p_type, TokenData * p_token, Expression * e1 OS_DBG_FILEPOS_DECL): list(p_token->getAllocator()) { token = p_token->retain(); type = p_type; list.add(e1 OS_DBG_FILEPOS_PARAM); ret_values = 0; active_locals = 0; } OS::Core::Compiler::Expression::Expression(ExpressionType p_type, TokenData * p_token, Expression * e1, Expression * e2 OS_DBG_FILEPOS_DECL): list(p_token->getAllocator()) { token = p_token->retain(); type = p_type; list.add(e1 OS_DBG_FILEPOS_PARAM); list.add(e2 OS_DBG_FILEPOS_PARAM); ret_values = 0; active_locals = 0; } OS::Core::Compiler::Expression::Expression(ExpressionType p_type, TokenData * p_token, Expression * e1, Expression * e2, Expression * e3 OS_DBG_FILEPOS_DECL): list(p_token->getAllocator()) { token = p_token->retain(); type = p_type; list.add(e1 OS_DBG_FILEPOS_PARAM); list.add(e2 OS_DBG_FILEPOS_PARAM); list.add(e3 OS_DBG_FILEPOS_PARAM); ret_values = 0; active_locals = 0; } OS::Core::Compiler::Expression::~Expression() { token->release(); } bool OS::Core::Compiler::Expression::isConstValue() const { switch(type){ // case EXP_TYPE_CODE_LIST: // return list.count ? list[list.count-1]->isValue() : false; case EXP_TYPE_CONST_STRING: case EXP_TYPE_CONST_NUMBER: case EXP_TYPE_CONST_NULL: case EXP_TYPE_CONST_TRUE: case EXP_TYPE_CONST_FALSE: // case EXP_TYPE_NAME: // case EXP_TYPE_CALL: OS_ASSERT(ret_values == 1); return true; } return false; } bool OS::Core::Compiler::Expression::isValue() const { return ret_values > 0; } bool OS::Core::Compiler::Expression::isClear() const { return ret_values == 0; } bool OS::Core::Compiler::Expression::isWriteable() const { switch(type){ // case EXP_TYPE_CODE_LIST: // return list.count ? list[list.count-1]->isWriteable() : false; case EXP_TYPE_NAME: case EXP_TYPE_INDIRECT: case EXP_TYPE_CALL_DIM: case EXP_TYPE_CALL_METHOD: return true; case EXP_TYPE_PARAMS: for(int i = 0; i < list.count; i++){ if(list[i]->type == EXP_TYPE_PARAMS || !list[i]->isWriteable()){ return false; } } return true; } return false; } bool OS::Core::Compiler::Expression::isOperator() const { return isBinaryOperator() || isUnaryOperator(); } bool OS::Core::Compiler::Expression::isUnaryOperator() const { switch(type){ case EXP_TYPE_LOGIC_BOOL: // !! case EXP_TYPE_LOGIC_NOT: // ! case EXP_TYPE_PLUS: // + case EXP_TYPE_NEG: // - case EXP_TYPE_LENGTH: // # // case EXP_TYPE_INC: // ++ //case EXP_TYPE_DEC: // -- case EXP_TYPE_PRE_INC: // ++ case EXP_TYPE_PRE_DEC: // -- case EXP_TYPE_POST_INC: // ++ case EXP_TYPE_POST_DEC: // -- case EXP_TYPE_BIT_NOT: // ~ return true; } return false; } bool OS::Core::Compiler::Expression::isLogicOperator() const { switch(type){ case EXP_TYPE_LOGIC_BOOL: // !! case EXP_TYPE_LOGIC_NOT: // ! case EXP_TYPE_LOGIC_AND: // && case EXP_TYPE_LOGIC_OR: // || case EXP_TYPE_LOGIC_PTR_EQ: // === case EXP_TYPE_LOGIC_PTR_NE: // !== case EXP_TYPE_LOGIC_EQ: // == case EXP_TYPE_LOGIC_NE: // != case EXP_TYPE_LOGIC_GE: // >= case EXP_TYPE_LOGIC_LE: // <= case EXP_TYPE_LOGIC_GREATER: // > case EXP_TYPE_LOGIC_LESS: // < return true; } return false; } bool OS::Core::Compiler::Expression::isBinaryOperator() const { switch(type){ case EXP_TYPE_INDIRECT: case EXP_TYPE_ASSIGN: case EXP_TYPE_PARAMS: case EXP_TYPE_QUESTION: case EXP_TYPE_IN: case EXP_TYPE_ISPROTOTYPEOF: case EXP_TYPE_IS: case EXP_TYPE_CONCAT: // .. case EXP_TYPE_LOGIC_AND: // && case EXP_TYPE_LOGIC_OR: // || case EXP_TYPE_LOGIC_PTR_EQ: // === case EXP_TYPE_LOGIC_PTR_NE: // !== case EXP_TYPE_LOGIC_EQ: // == case EXP_TYPE_LOGIC_NE: // != case EXP_TYPE_LOGIC_GE: // >= case EXP_TYPE_LOGIC_LE: // <= case EXP_TYPE_LOGIC_GREATER: // > case EXP_TYPE_LOGIC_LESS: // < case EXP_TYPE_BIT_AND: // & case EXP_TYPE_BIT_OR: // | case EXP_TYPE_BIT_XOR: // ^ case EXP_TYPE_BIT_AND_ASSIGN: // &= case EXP_TYPE_BIT_OR_ASSIGN: // |= case EXP_TYPE_BIT_XOR_ASSIGN: // ^= case EXP_TYPE_BIT_NOT_ASSIGN: // ~= case EXP_TYPE_ADD: // + case EXP_TYPE_SUB: // - case EXP_TYPE_MUL: // * case EXP_TYPE_DIV: // / case EXP_TYPE_MOD: // % case EXP_TYPE_LSHIFT: // << case EXP_TYPE_RSHIFT: // >> case EXP_TYPE_POW: // ** case EXP_TYPE_ADD_ASSIGN: // += case EXP_TYPE_SUB_ASSIGN: // -= case EXP_TYPE_MUL_ASSIGN: // *= case EXP_TYPE_DIV_ASSIGN: // /= case EXP_TYPE_MOD_ASSIGN: // %= case EXP_TYPE_LSHIFT_ASSIGN: // <<= case EXP_TYPE_RSHIFT_ASSIGN: // >>= case EXP_TYPE_POW_ASSIGN: // **= return true; } return isAssignOperator(); } bool OS::Core::Compiler::Expression::isAssignOperator() const { switch(type){ case EXP_TYPE_ASSIGN: // = case EXP_TYPE_BIT_AND_ASSIGN: // &= case EXP_TYPE_BIT_OR_ASSIGN: // |= case EXP_TYPE_BIT_XOR_ASSIGN: // ^= case EXP_TYPE_BIT_NOT_ASSIGN: // ~= case EXP_TYPE_ADD_ASSIGN: // += case EXP_TYPE_SUB_ASSIGN: // -= case EXP_TYPE_MUL_ASSIGN: // *= case EXP_TYPE_DIV_ASSIGN: // /= case EXP_TYPE_MOD_ASSIGN: // %= case EXP_TYPE_LSHIFT_ASSIGN: // <<= case EXP_TYPE_RSHIFT_ASSIGN: // >>= case EXP_TYPE_POW_ASSIGN: // **= return true; } return false; } void OS::Core::Compiler::Expression::debugPrint(StringBuffer& out, OS::Core::Compiler * compiler, int depth) { OS * allocator = getAllocator(); compiler->debugPrintSourceLine(out, token); int i; OS_CHAR * spaces = (OS_CHAR*)alloca(sizeof(OS_CHAR)*(depth*2+1)); for(i = 0; i < depth*2; i++){ spaces[i] = OS_TEXT(' '); } spaces[i] = OS_TEXT('\0'); const OS_CHAR * type_name; switch(type){ case EXP_TYPE_NOP: out += String::format(allocator, OS_TEXT("%snop\n"), spaces); break; case EXP_TYPE_CODE_LIST: type_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, type_name); for(i = 0; i < list.count; i++){ if(i > 0){ out += OS_TEXT("\n"); } // OS_ASSERT(i+1 == list.count ? list[i]->ret_values == ret_values : list[i]->ret_values == 0); list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, type_name, ret_values); break; case EXP_TYPE_IF: OS_ASSERT(list.count == 2 || list.count == 3); out += String::format(allocator, OS_TEXT("%sbegin if\n"), spaces); out += String::format(allocator, OS_TEXT("%s begin bool exp\n"), spaces); list[0]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end bool exp\n"), spaces); out += String::format(allocator, OS_TEXT("%s begin then\n"), spaces); list[1]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end then\n"), spaces); if(list.count == 3){ out += String::format(allocator, OS_TEXT("%s begin else\n"), spaces); list[2]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end else\n"), spaces); } out += String::format(allocator, OS_TEXT("%send if ret values %d\n"), spaces, ret_values); break; case EXP_TYPE_QUESTION: OS_ASSERT(list.count == 3); out += String::format(allocator, OS_TEXT("%sbegin question\n"), spaces); out += String::format(allocator, OS_TEXT("%s begin bool exp\n"), spaces); list[0]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end bool exp\n"), spaces); out += String::format(allocator, OS_TEXT("%s begin then value\n"), spaces); list[1]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end then value\n"), spaces); out += String::format(allocator, OS_TEXT("%s begin else value\n"), spaces); list[2]->debugPrint(out, compiler, depth+2); out += String::format(allocator, OS_TEXT("%s end else value\n"), spaces); out += String::format(allocator, OS_TEXT("%send question ret values %d\n"), spaces, ret_values); break; case EXP_TYPE_CONST_NUMBER: case EXP_TYPE_CONST_STRING: { const OS_CHAR * end = OS_TEXT(""); switch(token->type){ case Tokenizer::NUMBER: type_name = OS_TEXT("number "); break; case Tokenizer::STRING: type_name = OS_TEXT("string \""); end = OS_TEXT("\""); break; case Tokenizer::NAME: type_name = OS_TEXT("string \""); end = OS_TEXT("\""); break; default: type_name = OS_TEXT("???"); break; } out += String::format(allocator, OS_TEXT("%spush const %s%s%s\n"), spaces, type_name, token->str.toChar(), end); } break; case EXP_TYPE_CONST_NULL: case EXP_TYPE_CONST_TRUE: case EXP_TYPE_CONST_FALSE: out += String::format(allocator, OS_TEXT("%s%s\n"), spaces, getExpName(type)); break; case EXP_TYPE_NAME: out += String::format(allocator, OS_TEXT("%sname %s\n"), spaces, token->str.toChar()); break; case EXP_TYPE_PARAMS: out += String::format(allocator, OS_TEXT("%sbegin params %d\n"), spaces, list.count); for(i = 0; i < list.count; i++){ if(i > 0){ out += String::format(allocator, OS_TEXT("%s ,\n"), spaces); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send params ret values %d\n"), spaces, ret_values); break; case EXP_TYPE_ARRAY: out += String::format(allocator, OS_TEXT("%sbegin array %d\n"), spaces, list.count); for(i = 0; i < list.count; i++){ if(i > 0){ out += String::format(allocator, OS_TEXT("%s ,\n"), spaces); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send array\n"), spaces); break; case EXP_TYPE_OBJECT: out += String::format(allocator, OS_TEXT("%sbegin object %d\n"), spaces, list.count); for(i = 0; i < list.count; i++){ if(i > 0){ out += String::format(allocator, OS_TEXT("%s ,\n"), spaces); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send object\n"), spaces); break; case EXP_TYPE_OBJECT_SET_BY_NAME: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin set by name\n"), spaces); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send set by name: [%s]\n"), spaces, token->str.toChar()); break; case EXP_TYPE_OBJECT_SET_BY_INDEX: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin set by index\n"), spaces); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send set by index: [%d]\n"), spaces, (int)token->getFloat()); break; case EXP_TYPE_OBJECT_SET_BY_EXP: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin set by exp\n"), spaces); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send set by exp\n"), spaces); break; case EXP_TYPE_OBJECT_SET_BY_AUTO_INDEX: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin set auto index\n"), spaces); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send set auto index\n"), spaces); break; case EXP_TYPE_FUNCTION: { // OS_ASSERT(list.count >= 1); Scope * scope = dynamic_cast<Scope*>(this); OS_ASSERT(scope); out += String::format(allocator, OS_TEXT("%sbegin function\n"), spaces); if(scope->num_locals > 0){ out += String::format(allocator, OS_TEXT("%s begin locals, total %d\n"), spaces, scope->num_locals); for(i = 0; i < scope->locals.count; i++){ out += String::format(allocator, OS_TEXT("%s %d %s%s\n"), spaces, scope->locals[i].index, scope->locals[i].name.toChar(), i < scope->num_params ? OS_TEXT(" (param)") : OS_TEXT("") ); } out += String::format(allocator, OS_TEXT("%s end locals\n"), spaces); } for(i = 0; i < list.count; i++){ if(i > 0){ out += OS_TEXT("\n"); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send function\n"), spaces); break; } case EXP_TYPE_SCOPE: case EXP_TYPE_LOOP_SCOPE: { // OS_ASSERT(list.count >= 1); Scope * scope = dynamic_cast<Scope*>(this); OS_ASSERT(scope); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); if(scope->locals.count > 0){ out += String::format(allocator, OS_TEXT("%s begin locals %d\n"), spaces, scope->locals.count); for(i = 0; i < scope->locals.count; i++){ out += String::format(allocator, OS_TEXT("%s %d %s%s\n"), spaces, scope->locals[i].index, scope->locals[i].name.toChar(), i < scope->num_params ? OS_TEXT(" (param)") : OS_TEXT("") ); } out += String::format(allocator, OS_TEXT("%s end locals\n"), spaces); } for(i = 0; i < list.count; i++){ if(i > 0){ out += OS_TEXT("\n"); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, exp_name, ret_values); break; } case EXP_TYPE_RETURN: if(list.count > 0){ out += String::format(allocator, OS_TEXT("%sbegin return\n"), spaces); for(i = 0; i < list.count; i++){ if(i > 0){ out += String::format(allocator, OS_TEXT("%s ,\n"), spaces); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send return values %d\n"), spaces, ret_values); }else{ out += String::format(allocator, OS_TEXT("%sreturn\n"), spaces); } break; case EXP_TYPE_BREAK: OS_ASSERT(list.count == 0); out += String::format(allocator, OS_TEXT("%sbreak\n"), spaces); break; case EXP_TYPE_CONTINUE: OS_ASSERT(list.count == 0); out += String::format(allocator, OS_TEXT("%scontinue\n"), spaces); break; case EXP_TYPE_DEBUGGER: OS_ASSERT(list.count == 0); out += String::format(allocator, OS_TEXT("%sdebugger\n"), spaces); break; case EXP_TYPE_DEBUG_LOCALS: out += String::format(allocator, OS_TEXT("%sbegin debug locals\n"), spaces); for(i = 0; i < list.count; i++){ if(i > 0){ out += String::format(allocator, OS_TEXT("%s ,\n"), spaces); } list[i]->debugPrint(out, compiler, depth+1); } out += String::format(allocator, OS_TEXT("%send debug locals\n"), spaces); break; case EXP_TYPE_TAIL_CALL: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, OS::Core::Compiler::getExpName(type)); break; case EXP_TYPE_TAIL_CALL_METHOD: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, OS::Core::Compiler::getExpName(type)); break; case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, OS::Core::Compiler::getExpName(type), ret_values); break; case EXP_TYPE_CALL_DIM: // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: case EXP_TYPE_GET_PROPERTY: case EXP_TYPE_GET_PROPERTY_BY_LOCALS: case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: // case EXP_TYPE_GET_PROPERTY_DIM: // case EXP_TYPE_SET_ENV_VAR_DIM: case EXP_TYPE_EXTENDS: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, OS::Core::Compiler::getExpName(type), ret_values); break; case EXP_TYPE_DELETE: OS_ASSERT(list.count == 2); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, OS::Core::Compiler::getExpName(type)); break; case EXP_TYPE_CLONE: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, OS::Core::Compiler::getExpName(type)); break; case EXP_TYPE_VALUE: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, OS::Core::Compiler::getExpName(type)); break; case EXP_TYPE_POP_VALUE: OS_ASSERT(list.count == 1); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, OS::Core::Compiler::getExpName(type)); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, OS::Core::Compiler::getExpName(type), ret_values); break; case EXP_TYPE_SUPER: OS_ASSERT(list.count == 0); out += String::format(allocator, OS_TEXT("%ssuper\n"), spaces); break; case EXP_TYPE_TYPE_OF: case EXP_TYPE_VALUE_OF: case EXP_TYPE_NUMBER_OF: case EXP_TYPE_STRING_OF: case EXP_TYPE_ARRAY_OF: case EXP_TYPE_OBJECT_OF: case EXP_TYPE_USERDATA_OF: case EXP_TYPE_FUNCTION_OF: case EXP_TYPE_PLUS: // + case EXP_TYPE_NEG: // - case EXP_TYPE_LENGTH: // # case EXP_TYPE_LOGIC_BOOL: // !! case EXP_TYPE_LOGIC_NOT: // ! case EXP_TYPE_BIT_NOT: // ~ case EXP_TYPE_PRE_INC: // ++ case EXP_TYPE_PRE_DEC: // -- case EXP_TYPE_POST_INC: // ++ case EXP_TYPE_POST_DEC: // -- { OS_ASSERT(list.count == 1); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, exp_name); break; } case EXP_TYPE_INDIRECT: case EXP_TYPE_ASSIGN: case EXP_TYPE_CONCAT: // .. case EXP_TYPE_IN: case EXP_TYPE_ISPROTOTYPEOF: case EXP_TYPE_IS: case EXP_TYPE_LOGIC_AND: // && case EXP_TYPE_LOGIC_OR: // || case EXP_TYPE_LOGIC_PTR_EQ: // === case EXP_TYPE_LOGIC_PTR_NE: // !== case EXP_TYPE_LOGIC_EQ: // == case EXP_TYPE_LOGIC_NE: // != case EXP_TYPE_LOGIC_GE: // >= case EXP_TYPE_LOGIC_LE: // <= case EXP_TYPE_LOGIC_GREATER: // > case EXP_TYPE_LOGIC_LESS: // < case EXP_TYPE_BIT_AND: // & case EXP_TYPE_BIT_OR: // | case EXP_TYPE_BIT_XOR: // ^ // case EXP_TYPE_BIT_NOT: // ~ case EXP_TYPE_BIT_AND_ASSIGN: // &= case EXP_TYPE_BIT_OR_ASSIGN: // |= case EXP_TYPE_BIT_XOR_ASSIGN: // ^= case EXP_TYPE_BIT_NOT_ASSIGN: // ~= case EXP_TYPE_ADD: // + case EXP_TYPE_SUB: // - case EXP_TYPE_MUL: // * case EXP_TYPE_DIV: // / case EXP_TYPE_MOD: // % case EXP_TYPE_LSHIFT: // << case EXP_TYPE_RSHIFT: // >> case EXP_TYPE_POW: // ** case EXP_TYPE_ADD_ASSIGN: // += case EXP_TYPE_SUB_ASSIGN: // -= case EXP_TYPE_MUL_ASSIGN: // *= case EXP_TYPE_DIV_ASSIGN: // /= case EXP_TYPE_MOD_ASSIGN: // %= case EXP_TYPE_LSHIFT_ASSIGN: // <<= case EXP_TYPE_RSHIFT_ASSIGN: // >>= case EXP_TYPE_POW_ASSIGN: // **= { OS_ASSERT(list.count == 2); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, exp_name); break; } case EXP_TYPE_BIN_OPERATOR_BY_LOCALS: case EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER: { OS_ASSERT(list.count == 1); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s\n"), spaces, exp_name); break; } case EXP_TYPE_NEW_LOCAL_VAR: { OS_ASSERT(list.count == 0); String info = String::format(allocator, OS_TEXT("(%d %d%s)"), local_var.index, local_var.up_count, local_var.type == LOCAL_PARAM ? OS_TEXT(" param") : (local_var.type == LOCAL_TEMP ? OS_TEXT(" temp") : OS_TEXT(""))); out += String::format(allocator, OS_TEXT("%snew local var %s %s\n"), spaces, token->str.toChar(), info.toChar()); break; } case EXP_TYPE_GET_THIS: case EXP_TYPE_GET_ARGUMENTS: case EXP_TYPE_GET_REST_ARGUMENTS: { OS_ASSERT(list.count == 0); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%s%s\n"), spaces, exp_name); break; } case EXP_TYPE_GET_LOCAL_VAR: case EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE: { OS_ASSERT(list.count == 0); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); String info = String::format(allocator, OS_TEXT("(%d %d%s)"), local_var.index, local_var.up_count, local_var.type == LOCAL_PARAM ? OS_TEXT(" param") : (local_var.type == LOCAL_TEMP ? OS_TEXT(" temp") : OS_TEXT(""))); out += String::format(allocator, OS_TEXT("%s%s %s %s\n"), spaces, exp_name, token->str.toChar(), info.toChar()); break; } case EXP_TYPE_GET_ENV_VAR: case EXP_TYPE_GET_ENV_VAR_AUTO_CREATE: { OS_ASSERT(list.count == 0); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%s%s %s\n"), spaces, exp_name, token->str.toChar()); break; } case EXP_TYPE_SET_LOCAL_VAR: case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS: case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER: { OS_ASSERT(list.count == 1); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); String info = String::format(allocator, OS_TEXT("(%d %d%s)"), local_var.index, local_var.up_count, local_var.type == LOCAL_PARAM ? OS_TEXT(" param") : (local_var.type == LOCAL_TEMP ? OS_TEXT(" temp") : OS_TEXT(""))); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s %s %s\n"), spaces, exp_name, token->str.toChar(), info.toChar()); break; } case EXP_TYPE_SET_ENV_VAR: { OS_ASSERT(list.count == 1); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s %s\n"), spaces, exp_name, token->str.toChar()); break; } case EXP_TYPE_SET_PROPERTY: case EXP_TYPE_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: case EXP_TYPE_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: // case EXP_TYPE_SET_PROPERTY_DIM: case EXP_TYPE_SET_DIM: { OS_ASSERT(list.count == 3); const OS_CHAR * exp_name = OS::Core::Compiler::getExpName(type); out += String::format(allocator, OS_TEXT("%sbegin %s\n"), spaces, exp_name); list[0]->debugPrint(out, compiler, depth+1); list[1]->debugPrint(out, compiler, depth+1); list[2]->debugPrint(out, compiler, depth+1); out += String::format(allocator, OS_TEXT("%send %s ret values %d\n"), spaces, exp_name, ret_values); break; } } } // ===================================================================== int OS::Core::Compiler::cacheString(Table * strings_table, Vector<String>& strings, const String& str) { PropertyIndex index(str, PropertyIndex::KeepStringIndex()); Property * prop = strings_table->get(index); if(prop){ OS_ASSERT(prop->value.type == OS_VALUE_TYPE_NUMBER); return (int)prop->value.v.number; } prop = new (malloc(sizeof(Property) OS_DBG_FILEPOS)) Property(index); prop->value = Value(strings_table->count); allocator->core->addTableProperty(strings_table, prop); allocator->vectorAddItem(strings, str OS_DBG_FILEPOS); OS_ASSERT(strings_table->count == strings.count); return strings_table->count-1; } int OS::Core::Compiler::cacheString(const String& str) { return cacheString(prog_strings_table, prog_strings, str); } int OS::Core::Compiler::cacheDebugString(const String& str) { return cacheString(prog_debug_strings_table, prog_debug_strings, str); } int OS::Core::Compiler::cacheNumber(OS_NUMBER num) { PropertyIndex index(num); Property * prop = prog_numbers_table->get(index); if(prop){ OS_ASSERT(prop->value.type == OS_VALUE_TYPE_NUMBER); return (int)prop->value.v.number; } prop = new (malloc(sizeof(Property) OS_DBG_FILEPOS)) Property(index); prop->value = Value(prog_numbers_table->count); allocator->core->addTableProperty(prog_numbers_table, prop); allocator->vectorAddItem(prog_numbers, num OS_DBG_FILEPOS); OS_ASSERT(prog_numbers_table->count == prog_numbers.count); return prog_numbers_table->count-1; } void OS::Core::Compiler::writeDebugInfo(Expression * exp) { if(prog_debug_info){ prog_num_debug_infos++; prog_debug_info->writeUVariable(prog_opcodes->getPos()); prog_debug_info->writeUVariable(exp->token->line+1); prog_debug_info->writeUVariable(exp->token->pos+1); prog_debug_info->writeUVariable(cacheDebugString(exp->token->str)); } } bool OS::Core::Compiler::writeOpcodes(Scope * scope, ExpressionList& list) { for(int i = 0; i < list.count; i++){ if(!writeOpcodes(scope, list[i])){ return false; } } return true; } bool OS::Core::Compiler::writeOpcodes(Scope * scope, Expression * exp) { int i; // writeDebugInfo(exp); switch(exp->type){ default: { ExpressionType exp_type = exp->type; OS_ASSERT(false); break; } case EXP_TYPE_NOP: break; case EXP_TYPE_NEW_LOCAL_VAR: break; case EXP_TYPE_VALUE: case EXP_TYPE_CODE_LIST: if(!writeOpcodes(scope, exp->list)){ return false; } break; case EXP_TYPE_CONST_NUMBER: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_NUMBER); prog_opcodes->writeUVariable(cacheNumber((OS_NUMBER)exp->token->getFloat())); break; case EXP_TYPE_CONST_STRING: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_STRING); prog_opcodes->writeUVariable(cacheString(exp->token->str)); break; case EXP_TYPE_CONST_NULL: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_NULL); break; case EXP_TYPE_CONST_TRUE: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_TRUE); break; case EXP_TYPE_CONST_FALSE: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_FALSE); break; case EXP_TYPE_FUNCTION: { Scope * scope = dynamic_cast<Scope*>(exp); OS_ASSERT(scope); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_FUNCTION); int prog_func_index = scope->prog_func_index; // prog_functions.indexOf(scope); OS_ASSERT(prog_func_index >= 0); prog_opcodes->writeUVariable(prog_func_index); allocator->vectorReserveCapacity(scope->locals_compiled, scope->num_locals OS_DBG_FILEPOS); scope->locals_compiled.count = scope->num_locals; scope->opcodes_pos = prog_opcodes->getPos(); if(!writeOpcodes(scope, exp->list)){ return false; } prog_opcodes->writeByte(Program::OP_RETURN_AUTO); scope->opcodes_size = prog_opcodes->getPos() - scope->opcodes_pos; for(i = 0; i < scope->locals.count; i++){ Scope::LocalVar& var = scope->locals[i]; Scope::LocalVarCompiled& var_scope = scope->locals_compiled[var.index]; var_scope.cached_name_index = cacheString(var.name); var_scope.start_code_pos = scope->opcodes_pos; var_scope.end_code_pos = prog_opcodes->getPos(); } break; } case EXP_TYPE_SCOPE: case EXP_TYPE_LOOP_SCOPE: { Scope * scope = dynamic_cast<Scope*>(exp); OS_ASSERT(scope); int start_code_pos = prog_opcodes->getPos(); if(!writeOpcodes(scope, exp->list)){ return false; } if(exp->type == EXP_TYPE_LOOP_SCOPE){ prog_opcodes->writeByte(Program::OP_JUMP); prog_opcodes->writeInt32(start_code_pos - prog_opcodes->getPos() - sizeof(OS_INT32)); scope->fixLoopBreaks(start_code_pos, prog_opcodes->getPos(), prog_opcodes); }else{ OS_ASSERT(scope->loop_breaks.count == 0); } for(i = 0; i < scope->locals.count; i++){ Scope::LocalVar& var = scope->locals[i]; Scope::LocalVarCompiled& var_scope = scope->function->locals_compiled[var.index]; var_scope.cached_name_index = cacheString(var.name); var_scope.start_code_pos = start_code_pos; var_scope.end_code_pos = prog_opcodes->getPos(); } break; } case EXP_TYPE_IF: { OS_ASSERT(exp->list.count == 2 || exp->list.count == 3); if(exp->list[0]->type == EXP_TYPE_LOGIC_NOT){ OS_ASSERT(exp->list[0]->list.count == 1); if(!writeOpcodes(scope, exp->list[0]->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_IF_JUMP); }else{ if(!writeOpcodes(scope, exp->list[0])){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_IF_NOT_JUMP); } int if_not_jump_pos = prog_opcodes->getPos(); prog_opcodes->writeInt32(0); if(!writeOpcodes(scope, exp->list[1])){ return false; } int if_not_jump_to = prog_opcodes->getPos(); if(exp->list.count == 3 && exp->list[2]->list.count > 0){ prog_opcodes->writeByte(Program::OP_JUMP); int jump_pos = prog_opcodes->getPos(); prog_opcodes->writeInt32(0); if_not_jump_to = prog_opcodes->getPos(); if(!writeOpcodes(scope, exp->list[2])){ return false; } prog_opcodes->writeInt32AtPos(prog_opcodes->getPos() - jump_pos - sizeof(OS_INT32), jump_pos); } prog_opcodes->writeInt32AtPos(if_not_jump_to - if_not_jump_pos - sizeof(OS_INT32), if_not_jump_pos); break; } case EXP_TYPE_QUESTION: { OS_ASSERT(exp->list.count == 3); if(exp->list[0]->type == EXP_TYPE_LOGIC_NOT){ OS_ASSERT(exp->list[0]->list.count == 1); if(!writeOpcodes(scope, exp->list[0]->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_IF_JUMP); }else{ if(!writeOpcodes(scope, exp->list[0])){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_IF_NOT_JUMP); } int if_not_jump_pos = prog_opcodes->getPos(); prog_opcodes->writeInt32(0); if(!writeOpcodes(scope, exp->list[1])){ return false; } int if_not_jump_to = prog_opcodes->getPos(); prog_opcodes->writeByte(Program::OP_JUMP); int jump_pos = prog_opcodes->getPos(); prog_opcodes->writeInt32(0); if_not_jump_to = prog_opcodes->getPos(); if(!writeOpcodes(scope, exp->list[2])){ return false; } prog_opcodes->writeInt32AtPos(prog_opcodes->getPos() - jump_pos - sizeof(OS_INT32), jump_pos); prog_opcodes->writeInt32AtPos(if_not_jump_to - if_not_jump_pos - sizeof(OS_INT32), if_not_jump_pos); break; } case EXP_TYPE_LOGIC_AND: // && case EXP_TYPE_LOGIC_OR: // || { OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list[0])){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); int op_jump_pos = prog_opcodes->getPos(); prog_opcodes->writeInt32(0); if(!writeOpcodes(scope, exp->list[1])){ return false; } int op_jump_to = prog_opcodes->getPos(); prog_opcodes->writeInt32AtPos(op_jump_to - op_jump_pos - sizeof(OS_INT32), op_jump_pos); break; } case EXP_TYPE_EXTENDS: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_EXTENDS); break; case EXP_TYPE_CLONE: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_CLONE); break; case EXP_TYPE_DELETE: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_DELETE_PROP); break; case EXP_TYPE_ARRAY: writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_NEW_ARRAY); prog_opcodes->writeByte(exp->list.count > 255 ? 256 : exp->list.count); if(!writeOpcodes(scope, exp->list)){ return false; } break; case EXP_TYPE_OBJECT: // OS_ASSERT(exp->list.count >= 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_NEW_OBJECT); if(!writeOpcodes(scope, exp->list)){ return false; } break; case EXP_TYPE_OBJECT_SET_BY_AUTO_INDEX: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_OBJECT_SET_BY_AUTO_INDEX); break; case EXP_TYPE_OBJECT_SET_BY_EXP: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_OBJECT_SET_BY_EXP); break; case EXP_TYPE_OBJECT_SET_BY_INDEX: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_OBJECT_SET_BY_INDEX); // prog_opcodes->writeInt64(exp->token->getInt()); prog_opcodes->writeUVariable(cacheNumber((OS_NUMBER)exp->token->getFloat())); break; case EXP_TYPE_OBJECT_SET_BY_NAME: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_OBJECT_SET_BY_NAME); prog_opcodes->writeUVariable(cacheString(exp->token->str)); break; case EXP_TYPE_GET_ENV_VAR: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_ENV_VAR); prog_opcodes->writeUVariable(cacheString(exp->token->str)); break; case EXP_TYPE_GET_ENV_VAR_AUTO_CREATE: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_ENV_VAR_AUTO_CREATE); prog_opcodes->writeUVariable(cacheString(exp->token->str)); break; case EXP_TYPE_SET_ENV_VAR: OS_ASSERT(exp->list.count > 0); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_ENV_VAR); prog_opcodes->writeUVariable(cacheString(exp->token->str)); break; case EXP_TYPE_GET_THIS: case EXP_TYPE_GET_ARGUMENTS: case EXP_TYPE_GET_REST_ARGUMENTS: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); break; case EXP_TYPE_GET_LOCAL_VAR: OS_ASSERT(exp->list.count == 0); if(!exp->local_var.up_count){ writeDebugInfo(exp); if(exp->local_var.index <= 255){ prog_opcodes->writeByte(Program::OP_PUSH_LOCAL_VAR); prog_opcodes->writeByte(exp->local_var.index); }else{ prog_opcodes->writeByte(Program::OP_PUSH_LOCAL_VAR_BY_AUTO_INDEX); prog_opcodes->writeUVariable(exp->local_var.index); } }else{ writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_UP_LOCAL_VAR); prog_opcodes->writeUVariable(exp->local_var.index); prog_opcodes->writeByte(exp->local_var.up_count); } break; case EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE: OS_ASSERT(exp->list.count == 0); if(!exp->local_var.up_count){ writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_LOCAL_VAR_AUTO_CREATE); prog_opcodes->writeUVariable(exp->local_var.index); }else{ writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_UP_LOCAL_VAR_AUTO_CREATE); prog_opcodes->writeUVariable(exp->local_var.index); prog_opcodes->writeByte(exp->local_var.up_count); } break; case EXP_TYPE_SET_LOCAL_VAR: OS_ASSERT(exp->list.count > 0); if(!writeOpcodes(scope, exp->list)){ return false; } if(!exp->local_var.up_count){ writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_LOCAL_VAR); prog_opcodes->writeUVariable(exp->local_var.index); }else{ writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_UP_LOCAL_VAR); prog_opcodes->writeUVariable(exp->local_var.index); prog_opcodes->writeByte(exp->local_var.up_count); } break; case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS: { OS_ASSERT(exp->list.count == 1); OS_ASSERT(!exp->local_var.up_count); OS_ASSERT(exp->list[0]->type == EXP_TYPE_BIN_OPERATOR_BY_LOCALS); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS); Expression * exp_binary = exp->list[0]->list[0]; Expression * exp1 = exp_binary->list[0]; Expression * exp2 = exp_binary->list[1]; prog_opcodes->writeByte(Program::getOpcodeType(exp_binary->type)); prog_opcodes->writeByte(exp1->local_var.index); prog_opcodes->writeByte(exp2->local_var.index); prog_opcodes->writeUVariable(exp->local_var.index); break; } case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER: { OS_ASSERT(exp->list.count == 1); OS_ASSERT(!exp->local_var.up_count); OS_ASSERT(exp->list[0]->type == EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER); Expression * exp_binary = exp->list[0]->list[0]; Expression * exp1 = exp_binary->list[0]; Expression * exp2 = exp_binary->list[1]; prog_opcodes->writeByte(Program::getOpcodeType(exp_binary->type)); prog_opcodes->writeByte(exp1->local_var.index); prog_opcodes->writeUVariable(cacheNumber((OS_NUMBER)exp2->token->getFloat())); prog_opcodes->writeUVariable(exp->local_var.index); break; } case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: { OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[1]->type == EXP_TYPE_PARAMS); bool is_super_call = exp->list[0]->type == EXP_TYPE_SUPER; if(is_super_call){ prog_opcodes->writeByte(Program::OP_PUSH_NULL); // func }else if(!writeOpcodes(scope, exp->list[0])){ return false; } // writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_PUSH_NULL); // this if(!writeOpcodes(scope, exp->list[1])){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(is_super_call ? Program::OP_SUPER_CALL : Program::getOpcodeType(exp->type)); prog_opcodes->writeByte(exp->list[1]->ret_values); // params number prog_opcodes->writeByte(exp->ret_values); break; } case EXP_TYPE_TAIL_CALL: OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[1]->type == EXP_TYPE_PARAMS); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); prog_opcodes->writeByte(exp->list[1]->ret_values); // params number break; // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[1]->type == EXP_TYPE_PARAMS); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); prog_opcodes->writeByte(exp->list[1]->ret_values-1); // params number prog_opcodes->writeByte(exp->ret_values); break; case EXP_TYPE_TAIL_CALL_METHOD: OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[1]->type == EXP_TYPE_PARAMS); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); prog_opcodes->writeByte(exp->list[1]->ret_values-1); // params number break; case EXP_TYPE_GET_PROPERTY: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_GET_PROPERTY); prog_opcodes->writeByte(exp->ret_values); break; case EXP_TYPE_GET_PROPERTY_BY_LOCALS: OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[0]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->local_var.up_count); OS_ASSERT(exp->list[1]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[1]->local_var.up_count); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_GET_PROPERTY_BY_LOCALS); prog_opcodes->writeByte(exp->ret_values); prog_opcodes->writeByte(exp->list[0]->local_var.index); prog_opcodes->writeByte(exp->list[1]->local_var.index); break; case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: OS_ASSERT(exp->list.count == 2); OS_ASSERT(exp->list[0]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->local_var.up_count); OS_ASSERT(exp->list[1]->type == EXP_TYPE_CONST_NUMBER); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_GET_PROPERTY_BY_LOCAL_AND_NUMBER); prog_opcodes->writeByte(exp->ret_values); prog_opcodes->writeByte(exp->list[0]->local_var.index); prog_opcodes->writeUVariable(cacheNumber((OS_NUMBER)exp->list[1]->token->getFloat())); break; case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_GET_PROPERTY_AUTO_CREATE); prog_opcodes->writeByte(exp->ret_values); break; case EXP_TYPE_SET_PROPERTY: OS_ASSERT(exp->list.count == 3); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_PROPERTY); break; case EXP_TYPE_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: OS_ASSERT(exp->list.count == 3); OS_ASSERT(exp->list[1]->type == EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE && !exp->list[1]->local_var.up_count); OS_ASSERT(exp->list[2]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[2]->local_var.up_count); writeOpcodes(scope, exp->list[0]); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_PROPERTY_BY_LOCALS_AUTO_CREATE); prog_opcodes->writeByte(exp->list[1]->local_var.index); prog_opcodes->writeByte(exp->list[2]->local_var.index); break; case EXP_TYPE_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: OS_ASSERT(exp->list.count == 3); OS_ASSERT(exp->list[0]->type == EXP_TYPE_GET_PROPERTY_BY_LOCALS && exp->list[0]->list.count == 2); OS_ASSERT(exp->list[0]->list[0]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->list[0]->local_var.up_count); OS_ASSERT(exp->list[0]->list[1]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->list[1]->local_var.up_count); OS_ASSERT(exp->list[1]->type == EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE && !exp->list[1]->local_var.up_count); OS_ASSERT(exp->list[2]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[2]->local_var.up_count); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE); prog_opcodes->writeByte(exp->list[0]->list[0]->local_var.index); prog_opcodes->writeByte(exp->list[0]->list[1]->local_var.index); prog_opcodes->writeByte(exp->list[1]->local_var.index); prog_opcodes->writeByte(exp->list[2]->local_var.index); break; case EXP_TYPE_SET_DIM: OS_ASSERT(exp->list.count == 3); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SET_DIM); prog_opcodes->writeByte(exp->list[2]->list.count); // params break; case EXP_TYPE_PARAMS: if(!writeOpcodes(scope, exp->list)){ return false; } break; case EXP_TYPE_RETURN: if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_RETURN); prog_opcodes->writeByte(exp->ret_values); break; case EXP_TYPE_BREAK: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_JUMP); scope->addLoopBreak(prog_opcodes->getPos(), Scope::LOOP_BREAK); prog_opcodes->writeInt32(0); break; case EXP_TYPE_CONTINUE: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_JUMP); scope->addLoopBreak(prog_opcodes->getPos(), Scope::LOOP_CONTINUE); prog_opcodes->writeInt32(0); break; case EXP_TYPE_DEBUGGER: { OS_ASSERT(exp->list.count == 0); prog_opcodes->writeByte(Program::OP_DEBUGGER); prog_opcodes->writeUVariable(exp->token->line + 1); prog_opcodes->writeUVariable(exp->token->pos + 1); prog_opcodes->writeUVariable(OS_DEBUGGER_SAVE_NUM_LINES); Core::String empty(allocator); for(int i = 0; i < OS_DEBUGGER_SAVE_NUM_LINES; i++){ int j = exp->token->line - OS_DEBUGGER_SAVE_NUM_LINES/2 + i; if(j >= 0 && j < exp->token->text_data->lines.count){ prog_opcodes->writeUVariable(cacheString(exp->token->text_data->lines[j])); }else{ prog_opcodes->writeUVariable(cacheString(empty)); } } break; } case EXP_TYPE_DEBUG_LOCALS: if(!writeOpcodes(scope, exp->list)){ return false; } break; case EXP_TYPE_POP_VALUE: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } // writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_POP); break; case EXP_TYPE_SUPER: OS_ASSERT(exp->list.count == 0); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_SUPER); break; case EXP_TYPE_TYPE_OF: case EXP_TYPE_VALUE_OF: case EXP_TYPE_NUMBER_OF: case EXP_TYPE_STRING_OF: case EXP_TYPE_ARRAY_OF: case EXP_TYPE_OBJECT_OF: case EXP_TYPE_USERDATA_OF: case EXP_TYPE_FUNCTION_OF: case EXP_TYPE_LOGIC_BOOL: case EXP_TYPE_LOGIC_NOT: case EXP_TYPE_BIT_NOT: case EXP_TYPE_PLUS: case EXP_TYPE_NEG: case EXP_TYPE_LENGTH: OS_ASSERT(exp->list.count == 1); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); break; case EXP_TYPE_CONCAT: case EXP_TYPE_IN: case EXP_TYPE_ISPROTOTYPEOF: case EXP_TYPE_IS: // case EXP_TYPE_LOGIC_AND: // case EXP_TYPE_LOGIC_OR: case EXP_TYPE_LOGIC_PTR_EQ: case EXP_TYPE_LOGIC_PTR_NE: case EXP_TYPE_LOGIC_EQ: case EXP_TYPE_LOGIC_NE: case EXP_TYPE_LOGIC_GE: case EXP_TYPE_LOGIC_LE: case EXP_TYPE_LOGIC_GREATER: case EXP_TYPE_LOGIC_LESS: case EXP_TYPE_BIT_AND: case EXP_TYPE_BIT_OR: case EXP_TYPE_BIT_XOR: case EXP_TYPE_ADD: case EXP_TYPE_SUB: case EXP_TYPE_MUL: case EXP_TYPE_DIV: case EXP_TYPE_MOD: case EXP_TYPE_LSHIFT: case EXP_TYPE_RSHIFT: case EXP_TYPE_POW: OS_ASSERT(exp->list.count == 2); if(!writeOpcodes(scope, exp->list)){ return false; } writeDebugInfo(exp); prog_opcodes->writeByte(Program::getOpcodeType(exp->type)); break; case EXP_TYPE_BIN_OPERATOR_BY_LOCALS: { OS_ASSERT(exp->list.count == 1); OS_ASSERT(exp->list[0]->isBinaryOperator()); OS_ASSERT(exp->list[0]->list[0]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->list[0]->local_var.up_count); OS_ASSERT(exp->list[0]->list[1]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->list[1]->local_var.up_count); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_BIN_OPERATOR_BY_LOCALS); Expression * exp_binary = exp->list[0]; Expression * exp1 = exp_binary->list[0]; Expression * exp2 = exp_binary->list[1]; prog_opcodes->writeByte(Program::getOpcodeType(exp_binary->type)); prog_opcodes->writeByte(exp1->local_var.index); prog_opcodes->writeByte(exp2->local_var.index); break; } case EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER: { OS_ASSERT(exp->list.count == 1); OS_ASSERT(exp->list[0]->isBinaryOperator()); OS_ASSERT(exp->list[0]->list[0]->type == EXP_TYPE_GET_LOCAL_VAR && !exp->list[0]->list[0]->local_var.up_count); OS_ASSERT(exp->list[0]->list[1]->type == EXP_TYPE_CONST_NUMBER); writeDebugInfo(exp); prog_opcodes->writeByte(Program::OP_BIN_OPERATOR_BY_LOCAL_AND_NUMBER); Expression * exp_binary = exp->list[0]; Expression * exp1 = exp_binary->list[0]; Expression * exp2 = exp_binary->list[1]; prog_opcodes->writeByte(Program::getOpcodeType(exp_binary->type)); prog_opcodes->writeByte(exp1->local_var.index); prog_opcodes->writeUVariable(cacheNumber((OS_NUMBER)exp2->token->getFloat())); break; } } return true; } // ===================================================================== OS::Core::Compiler::Scope::Scope(Scope * p_parent, ExpressionType type, TokenData * token): Expression(type, token) { OS_ASSERT(type == EXP_TYPE_FUNCTION || type == EXP_TYPE_SCOPE || type == EXP_TYPE_LOOP_SCOPE); parent = p_parent; function = type == EXP_TYPE_FUNCTION ? this : parent->function; num_params = 0; num_locals = 0; max_up_count = 0; func_depth = 0; func_index = 0; num_local_funcs = 0; prog_func_index = -1; parser_started = false; } OS::Core::Compiler::Scope::~Scope() { getAllocator()->vectorClear(locals); getAllocator()->vectorClear(locals_compiled); getAllocator()->vectorClear(loop_breaks); } OS::Core::Compiler::Scope::LocalVar::LocalVar(const String& p_name, int p_index): name(p_name) { index = p_index; } OS::Core::Compiler::Scope::LocalVarCompiled::LocalVarCompiled() { cached_name_index = -1; start_code_pos = -1; end_code_pos = -1; } bool OS::Core::Compiler::Scope::addLoopBreak(int pos, ELoopBreakType type) { Scope * scope = this; for(; scope; scope = scope->parent){ if(scope->type == EXP_TYPE_LOOP_SCOPE){ break; } } if(!scope){ return false; } LoopBreak loop_break; loop_break.pos = pos; loop_break.type = type; getAllocator()->vectorAddItem(scope->loop_breaks, loop_break OS_DBG_FILEPOS); return true; } void OS::Core::Compiler::Scope::fixLoopBreaks(int scope_start_pos, int scope_end_pos, StreamWriter * writer) { for(int i = 0; i < loop_breaks.count; i++){ LoopBreak& loop_break = loop_breaks[i]; if(loop_break.type == LOOP_BREAK){ int offs = scope_end_pos - loop_break.pos - sizeof(OS_INT32); writer->writeInt32AtPos(offs, loop_break.pos); }else{ int offs = scope_start_pos - loop_break.pos - sizeof(OS_INT32); writer->writeInt32AtPos(offs, loop_break.pos); } } } void OS::Core::Compiler::Scope::addStdVars() { OS_ASSERT(ENV_VAR_INDEX == 0); Core::Strings * strings = getAllocator()->core->strings; // don't change following order addLocalVar(strings->var_env); #ifdef OS_GLOBAL_VAR_ENABLED OS_ASSERT(GLOBALS_VAR_INDEX == 1); addLocalVar(strings->var_globals); #endif } void OS::Core::Compiler::Scope::addLocalVar(const String& name) { OS * allocator = getAllocator(); LocalVar local_var(name, function->num_locals); allocator->vectorAddItem(locals, local_var OS_DBG_FILEPOS); function->num_locals++; } void OS::Core::Compiler::Scope::addLocalVar(const String& name, LocalVarDesc& local_var) { local_var.index = function->num_locals; local_var.up_count = 0; local_var.type = LOCAL_GENERIC; addLocalVar(name); } // ===================================================================== OS::Core::Compiler::Compiler(Tokenizer * p_tokenizer) : expect_token(p_tokenizer->getAllocator()) { allocator = p_tokenizer->getAllocator(); tokenizer = p_tokenizer; error = ERROR_NOTHING; error_token = NULL; expect_token_type = Tokenizer::NOTHING; recent_token = NULL; next_token_index = 0; recent_printed_text_data = NULL; recent_printed_line = 0; // prog = NULL; prog_strings_table = NULL; prog_debug_strings_table = NULL; prog_numbers_table = NULL; prog_opcodes = NULL; prog_debug_info = NULL; prog_num_debug_infos = 0; prog_max_up_count = 0; } OS::Core::Compiler::~Compiler() { if(recent_printed_text_data){ recent_printed_text_data->release(); } if(prog_numbers_table){ allocator->core->deleteTable(prog_numbers_table); prog_numbers_table = NULL; } if(prog_strings_table){ allocator->core->deleteTable(prog_strings_table); prog_strings_table = NULL; } if(prog_debug_strings_table){ allocator->core->deleteTable(prog_debug_strings_table); prog_debug_strings_table = NULL; } allocator->vectorClear(prog_numbers); allocator->vectorClear(prog_strings); allocator->vectorClear(prog_debug_strings); allocator->vectorClear(prog_functions); allocator->deleteObj(prog_opcodes); allocator->deleteObj(prog_debug_info); // allocator->deleteObj(tokenizer); } bool OS::Core::Compiler::compile() { OS_ASSERT(!prog_opcodes && !prog_strings_table && !prog_debug_strings_table && !prog_numbers_table); OS_ASSERT(!prog_functions.count && !prog_numbers.count && !prog_strings.count); Scope * scope = NULL; if(tokenizer->isError()){ setError(ERROR_SYNTAX, NULL); }else if(!readToken()){ setError(ERROR_EXPECT_TOKEN, recent_token); }else{ scope = expectTextExpression(); } if(scope){ Expression * exp = postProcessExpression(scope, scope); OS_ASSERT(exp->type == EXP_TYPE_FUNCTION); prog_strings_table = allocator->core->newTable(OS_DBG_FILEPOS_START); prog_numbers_table = allocator->core->newTable(OS_DBG_FILEPOS_START); prog_opcodes = new (malloc(sizeof(MemStreamWriter) OS_DBG_FILEPOS)) MemStreamWriter(allocator); OS::String filename(allocator, tokenizer->getTextData()->filename); bool is_eval = filename.getDataSize() == 0; if(!is_eval && allocator->core->settings.create_debug_opcodes){ Core::StringBuffer dump(allocator); exp->debugPrint(dump, this, 0); OS::String dump_filename = allocator->getDebugOpcodesFilename(filename); FileStreamWriter(allocator, dump_filename).writeBytes(dump.buf, dump.count * sizeof(OS_CHAR)); } prog_debug_strings_table = allocator->core->newTable(OS_DBG_FILEPOS_START); prog_debug_info = new (malloc(sizeof(MemStreamWriter) OS_DBG_FILEPOS)) MemStreamWriter(allocator); if(!writeOpcodes(scope, exp)){ // TODO: } MemStreamWriter mem_writer(allocator); MemStreamWriter debuginfo_mem_writer(allocator); saveToStream(&mem_writer, &debuginfo_mem_writer); if(!is_eval && allocator->core->settings.create_compiled_file){ OS::String compiled_filename = allocator->getCompiledFilename(filename); FileStreamWriter(allocator, compiled_filename).writeBytes(mem_writer.buffer.buf, mem_writer.buffer.count); if(allocator->core->settings.create_debug_info){ OS::String debug_info_filename = allocator->getDebugInfoFilename(filename); FileStreamWriter(allocator, debug_info_filename).writeBytes(debuginfo_mem_writer.buffer.buf, debuginfo_mem_writer.buffer.count); } } Program * prog = new (malloc(sizeof(Program) OS_DBG_FILEPOS)) Program(allocator); prog->filename = tokenizer->getTextData()->filename; MemStreamReader mem_reader(NULL, mem_writer.buffer.buf, mem_writer.buffer.count); MemStreamReader debuginfo_mem_reader(NULL, debuginfo_mem_writer.buffer.buf, debuginfo_mem_writer.buffer.count); prog->loadFromStream(&mem_reader, &debuginfo_mem_reader); prog->pushStartFunction(); prog->release(); allocator->deleteObj(exp); return true; }else{ Core::StringBuffer dump(allocator); dump += OS_TEXT("Error"); switch(error){ default: dump += OS_TEXT(" unknown"); break; case ERROR_SYNTAX: dump += OS_TEXT(" SYNTAX"); break; case ERROR_NESTED_ROOT_BLOCK: dump += OS_TEXT(" NESTED_ROOT_BLOCK"); break; case ERROR_LOCAL_VAL_NOT_DECLARED: dump += OS_TEXT(" LOCAL_VAL_NOT_DECLARED"); break; case ERROR_VAR_ALREADY_EXIST: dump += OS_TEXT(" VAR_ALREADY_EXIST"); break; case ERROR_VAR_NAME: dump += OS_TEXT(" VAR_NAME"); break; case ERROR_EXPECT_TOKEN_TYPE: dump += OS_TEXT(" EXPECT_TOKEN_TYPE "); dump += Tokenizer::getTokenTypeName(expect_token_type); break; case ERROR_EXPECT_TOKEN_STR: dump += OS_TEXT(" EXPECT_TOKEN_STR "); dump += expect_token; break; case ERROR_EXPECT_TOKEN: dump += OS_TEXT(" EXPECT_TOKEN"); break; case ERROR_EXPECT_VALUE: dump += OS_TEXT(" EXPECT_VALUE"); break; case ERROR_EXPECT_WRITEABLE: dump += OS_TEXT(" EXPECT_WRITEABLE"); break; case ERROR_EXPECT_GET_OR_SET: dump += OS_TEXT(" EXPECT_GET_OR_SET"); break; case ERROR_EXPECT_EXPRESSION: dump += OS_TEXT(" EXPECT_EXPRESSION"); break; case ERROR_EXPECT_FUNCTION_SCOPE: dump += OS_TEXT(" EXPECT_FUNCTION_SCOPE"); break; case ERROR_EXPECT_CODE_SEP_BEFORE_NESTED_BLOCK: dump += OS_TEXT(" EXPECT_CODE_SEP_BEFORE_NESTED_BLOCK"); break; case ERROR_EXPECT_SWITCH_SCOPE: dump += OS_TEXT(" EXPECT_SWITCH_SCOPE"); break; case ERROR_FINISH_BINARY_OP: dump += OS_TEXT(" FINISH_BINARY_OP"); break; case ERROR_FINISH_UNARY_OP: dump += OS_TEXT(" FINISH_UNARY_OP"); break; } dump += OS_TEXT("\n"); if(error_token){ if(error_token->text_data->filename.getDataSize() > 0){ dump += OS::Core::String::format(allocator, "filename %s\n", error_token->text_data->filename.toChar()); } dump += OS::Core::String::format(allocator, "[%d] %s\n", error_token->line+1, error_token->text_data->lines[error_token->line].toChar()); dump += OS::Core::String::format(allocator, "pos %d, token: %s\n", error_token->pos+1, error_token->str.toChar()); }else if(tokenizer->isError()){ if(tokenizer->getFilename().getDataSize() > 0){ dump += OS::Core::String::format(allocator, "filename %s\n", tokenizer->getFilename().toChar()); } dump += OS::Core::String::format(allocator, "[%d] %s\n", tokenizer->getErrorLine()+1, tokenizer->getLineString(tokenizer->getErrorLine()).toChar()); dump += OS::Core::String::format(allocator, "pos %d\n", tokenizer->getErrorPos()+1); } allocator->printf("%s", dump.toString().toChar()); // FileStreamWriter(allocator, "test-data/debug-exp-dump.txt").writeBytes(dump.toChar(), dump.getDataSize()); allocator->pushNull(); } return false; } void * OS::Core::Compiler::malloc(int size OS_DBG_FILEPOS_DECL) { return allocator->malloc(size OS_DBG_FILEPOS_PARAM); } void OS::Core::Compiler::resetError() { error = ERROR_NOTHING; error_token = NULL; expect_token_type = Tokenizer::NOTHING; } void OS::Core::Compiler::setError(ErrorType value, TokenData * error_token) { OS_ASSERT(!isError()); error = value; this->error_token = error_token; expect_token_type = Tokenizer::NOTHING; } void OS::Core::Compiler::setError(TokenType expect_token_type, TokenData * error_token) { OS_ASSERT(!isError()); error = ERROR_EXPECT_TOKEN_TYPE; this->error_token = error_token; this->expect_token_type = expect_token_type; } void OS::Core::Compiler::setError(const String& str, TokenData * error_token) { OS_ASSERT(!isError()); error = ERROR_EXPECT_TOKEN_STR; this->error_token = error_token; expect_token_type = Tokenizer::NOTHING; expect_token = str; } bool OS::Core::Compiler::isError() { return error != ERROR_NOTHING; } OS::Core::Compiler::ExpressionType OS::Core::Compiler::getUnaryExpressionType(TokenType token_type) { switch(token_type){ case Tokenizer::OPERATOR_LENGTH: return EXP_TYPE_LENGTH; case Tokenizer::OPERATOR_BIT_NOT: return EXP_TYPE_BIT_NOT; case Tokenizer::OPERATOR_ADD: return EXP_TYPE_PLUS; case Tokenizer::OPERATOR_SUB: return EXP_TYPE_NEG; case Tokenizer::OPERATOR_LOGIC_NOT: return EXP_TYPE_LOGIC_NOT; } return EXP_TYPE_UNKNOWN; } OS::Core::Compiler::ExpressionType OS::Core::Compiler::getExpressionType(TokenType token_type) { switch(token_type){ case Tokenizer::PARAM_SEPARATOR: return EXP_TYPE_PARAMS; case Tokenizer::OPERATOR_INDIRECT: return EXP_TYPE_INDIRECT; case Tokenizer::OPERATOR_CONCAT: return EXP_TYPE_CONCAT; case Tokenizer::OPERATOR_LENGTH: return EXP_TYPE_LENGTH; case Tokenizer::OPERATOR_LOGIC_AND: return EXP_TYPE_LOGIC_AND; case Tokenizer::OPERATOR_LOGIC_OR: return EXP_TYPE_LOGIC_OR; case Tokenizer::OPERATOR_LOGIC_PTR_EQ: return EXP_TYPE_LOGIC_PTR_EQ; case Tokenizer::OPERATOR_LOGIC_PTR_NE: return EXP_TYPE_LOGIC_PTR_NE; case Tokenizer::OPERATOR_LOGIC_EQ: return EXP_TYPE_LOGIC_EQ; case Tokenizer::OPERATOR_LOGIC_NE: return EXP_TYPE_LOGIC_NE; case Tokenizer::OPERATOR_LOGIC_GE: return EXP_TYPE_LOGIC_GE; case Tokenizer::OPERATOR_LOGIC_LE: return EXP_TYPE_LOGIC_LE; case Tokenizer::OPERATOR_LOGIC_GREATER: return EXP_TYPE_LOGIC_GREATER; case Tokenizer::OPERATOR_LOGIC_LESS: return EXP_TYPE_LOGIC_LESS; case Tokenizer::OPERATOR_LOGIC_NOT: return EXP_TYPE_LOGIC_NOT; // case Tokenizer::OPERATOR_INC: return EXP_TYPE_INC; // case Tokenizer::OPERATOR_DEC: return EXP_TYPE_DEC; case Tokenizer::OPERATOR_QUESTION: return EXP_TYPE_QUESTION; // case Tokenizer::OPERATOR_COLON: return ; case Tokenizer::OPERATOR_IN: return EXP_TYPE_IN; case Tokenizer::OPERATOR_ISPROTOTYPEOF: return EXP_TYPE_ISPROTOTYPEOF; case Tokenizer::OPERATOR_IS: return EXP_TYPE_IS; case Tokenizer::OPERATOR_BIT_AND: return EXP_TYPE_BIT_AND; case Tokenizer::OPERATOR_BIT_OR: return EXP_TYPE_BIT_OR; case Tokenizer::OPERATOR_BIT_XOR: return EXP_TYPE_BIT_XOR; case Tokenizer::OPERATOR_BIT_NOT: return EXP_TYPE_BIT_NOT; case Tokenizer::OPERATOR_ADD: return EXP_TYPE_ADD; case Tokenizer::OPERATOR_SUB: return EXP_TYPE_SUB; case Tokenizer::OPERATOR_MUL: return EXP_TYPE_MUL; case Tokenizer::OPERATOR_DIV: return EXP_TYPE_DIV; case Tokenizer::OPERATOR_MOD: return EXP_TYPE_MOD; case Tokenizer::OPERATOR_LSHIFT: return EXP_TYPE_LSHIFT; case Tokenizer::OPERATOR_RSHIFT: return EXP_TYPE_RSHIFT; case Tokenizer::OPERATOR_POW: return EXP_TYPE_POW; case Tokenizer::OPERATOR_BIT_AND_ASSIGN: return EXP_TYPE_BIT_AND_ASSIGN; case Tokenizer::OPERATOR_BIT_OR_ASSIGN: return EXP_TYPE_BIT_OR_ASSIGN; case Tokenizer::OPERATOR_BIT_XOR_ASSIGN: return EXP_TYPE_BIT_XOR_ASSIGN; case Tokenizer::OPERATOR_BIT_NOT_ASSIGN: return EXP_TYPE_BIT_NOT_ASSIGN; case Tokenizer::OPERATOR_ADD_ASSIGN: return EXP_TYPE_ADD_ASSIGN; case Tokenizer::OPERATOR_SUB_ASSIGN: return EXP_TYPE_SUB_ASSIGN; case Tokenizer::OPERATOR_MUL_ASSIGN: return EXP_TYPE_MUL_ASSIGN; case Tokenizer::OPERATOR_DIV_ASSIGN: return EXP_TYPE_DIV_ASSIGN; case Tokenizer::OPERATOR_MOD_ASSIGN: return EXP_TYPE_MOD_ASSIGN; case Tokenizer::OPERATOR_LSHIFT_ASSIGN: return EXP_TYPE_LSHIFT_ASSIGN; case Tokenizer::OPERATOR_RSHIFT_ASSIGN: return EXP_TYPE_RSHIFT_ASSIGN; case Tokenizer::OPERATOR_POW_ASSIGN: return EXP_TYPE_POW_ASSIGN; case Tokenizer::OPERATOR_ASSIGN: return EXP_TYPE_ASSIGN; } return EXP_TYPE_UNKNOWN; } OS::Core::Compiler::OpcodeLevel OS::Core::Compiler::getOpcodeLevel(ExpressionType exp_type) { switch(exp_type){ case EXP_TYPE_ASSIGN: // = case EXP_TYPE_BIT_AND_ASSIGN: // &= case EXP_TYPE_BIT_OR_ASSIGN: // |= case EXP_TYPE_BIT_XOR_ASSIGN: // ^= case EXP_TYPE_BIT_NOT_ASSIGN: // ~= case EXP_TYPE_ADD_ASSIGN: // += case EXP_TYPE_SUB_ASSIGN: // -= case EXP_TYPE_MUL_ASSIGN: // *= case EXP_TYPE_DIV_ASSIGN: // /= case EXP_TYPE_MOD_ASSIGN: // %= case EXP_TYPE_LSHIFT_ASSIGN: // <<= case EXP_TYPE_RSHIFT_ASSIGN: // >>= case EXP_TYPE_POW_ASSIGN: // **= return OP_LEVEL_1; case EXP_TYPE_PARAMS: // , return OP_LEVEL_1_1; case EXP_TYPE_QUESTION: // ? : return OP_LEVEL_2; case EXP_TYPE_LOGIC_OR: // || return OP_LEVEL_3; case EXP_TYPE_LOGIC_AND: // && return OP_LEVEL_4; case EXP_TYPE_CONCAT: // .. return OP_LEVEL_5; case EXP_TYPE_LOGIC_PTR_EQ: // === case EXP_TYPE_LOGIC_PTR_NE: // !== case EXP_TYPE_LOGIC_EQ: // == case EXP_TYPE_LOGIC_NE: // != return OP_LEVEL_6; case EXP_TYPE_LOGIC_GE: // >= case EXP_TYPE_LOGIC_LE: // <= case EXP_TYPE_LOGIC_GREATER: // > case EXP_TYPE_LOGIC_LESS: // < return OP_LEVEL_7; case EXP_TYPE_BIT_OR: // | return OP_LEVEL_8; case EXP_TYPE_BIT_AND: // & case EXP_TYPE_BIT_XOR: // ^ return OP_LEVEL_9; case EXP_TYPE_LSHIFT: // << case EXP_TYPE_RSHIFT: // >> return OP_LEVEL_10; case EXP_TYPE_ADD: // + case EXP_TYPE_SUB: // - return OP_LEVEL_11; case EXP_TYPE_MUL: // * case EXP_TYPE_DIV: // / case EXP_TYPE_MOD: // % return OP_LEVEL_12; case EXP_TYPE_POW: // ** case EXP_TYPE_IN: case EXP_TYPE_ISPROTOTYPEOF: case EXP_TYPE_IS: return OP_LEVEL_13; case EXP_TYPE_PRE_INC: // ++ case EXP_TYPE_PRE_DEC: // -- case EXP_TYPE_POST_INC: // ++ case EXP_TYPE_POST_DEC: // -- return OP_LEVEL_14; case EXP_TYPE_TYPE_OF: case EXP_TYPE_VALUE_OF: case EXP_TYPE_NUMBER_OF: case EXP_TYPE_STRING_OF: case EXP_TYPE_ARRAY_OF: case EXP_TYPE_OBJECT_OF: case EXP_TYPE_USERDATA_OF: case EXP_TYPE_FUNCTION_OF: case EXP_TYPE_LOGIC_BOOL: // !! case EXP_TYPE_LOGIC_NOT: // ! case EXP_TYPE_PLUS: // + case EXP_TYPE_NEG: // - case EXP_TYPE_LENGTH: // # case EXP_TYPE_BIT_NOT: // ~ return OP_LEVEL_15; case EXP_TYPE_INDIRECT: return OP_LEVEL_16; } return OP_LEVEL_0; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::getPrevToken() { int i = next_token_index-2; return i >= 0 ? tokenizer->getToken(i) : NULL; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::readToken() { if(isError()){ return NULL; } if(next_token_index < tokenizer->getNumTokens()){ return recent_token = tokenizer->getToken(next_token_index++); } return recent_token = NULL; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::setNextTokenIndex(int i) { OS_ASSERT(tokenizer && i >= 0 && i <= tokenizer->getNumTokens()); next_token_index = i; return recent_token = next_token_index > 0 ? tokenizer->getToken(next_token_index-1) : NULL; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::setNextToken(TokenData * token) { OS_ASSERT(tokenizer); int i, count = tokenizer->getNumTokens(); for(i = next_token_index - 1; i >= 0; i--){ if(tokenizer->getToken(i) == token) break; } if(i < 0){ for(i = next_token_index; i < count; i++){ if(tokenizer->getToken(i) == token) break; } } if(i >= 0 && i < count){ next_token_index = i; return recent_token = next_token_index > 0 ? tokenizer->getToken(next_token_index-1) : NULL; } OS_ASSERT(false); return NULL; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::putNextTokenType(TokenType token_type) { if(token_type == Tokenizer::CODE_SEPARATOR && recent_token && recent_token->type == token_type){ return ungetToken(); } TokenData * token = recent_token; if(readToken()){ if(recent_token->type == token_type){ return ungetToken(); } ungetToken(); token = recent_token; } if(!token){ if(next_token_index > 0){ token = tokenizer->getToken(next_token_index-1); } } if(token){ token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(token->text_data, String(allocator), token_type, token->line, token->pos); }else{ token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), String(allocator), token_type, 0, 0); } tokenizer->insertToken(next_token_index, token OS_DBG_FILEPOS); return token; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::ungetToken() { return setNextTokenIndex(next_token_index-1); } bool OS::Core::Compiler::isNextTokens(TokenType * list, int count) { bool ok = true; int save_next_token_index = next_token_index; for(int i = 0; i < count; i++){ if(!readToken() || !recent_token->isTypeOf(list[i])){ ok = false; break; } } setNextTokenIndex(save_next_token_index); return ok; } bool OS::Core::Compiler::isNextToken(TokenType t0) { return isNextTokens(&t0, 1); } bool OS::Core::Compiler::isNextTokens(TokenType t0, TokenType t1) { TokenType list[] = {t0, t1}; return isNextTokens(list, sizeof(list)/sizeof(list[0])); } bool OS::Core::Compiler::isNextTokens(TokenType t0, TokenType t1, TokenType t2) { TokenType list[] = {t0, t1, t2}; return isNextTokens(list, sizeof(list)/sizeof(list[0])); } bool OS::Core::Compiler::isNextTokens(TokenType t0, TokenType t1, TokenType t2, TokenType t3) { TokenType list[] = {t0, t1, t2, t3}; return isNextTokens(list, sizeof(list)/sizeof(list[0])); } void OS::Core::Compiler::deleteNops(ExpressionList& list) { for(int i = 0; i < list.count; i++){ Expression * exp = list[i]; switch(exp->type){ case EXP_TYPE_NOP: allocator->deleteObj(exp); list.removeIndex(i--); break; } } } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::expectToken(TokenType type) { if(isError()){ return NULL; } if(!readToken() || recent_token->type != type){ setError(type, recent_token); return NULL; } return recent_token; } OS::Core::Tokenizer::TokenData * OS::Core::Compiler::expectToken() { if(isError()){ return NULL; } if(!readToken()){ setError(ERROR_EXPECT_TOKEN, recent_token); return NULL; } return recent_token; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectExpressionValues(Expression * exp, int ret_values) { if(exp->ret_values == ret_values || ret_values < 0){ return exp; } switch(exp->type){ case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: case EXP_TYPE_CALL_DIM: // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: case EXP_TYPE_GET_PROPERTY: case EXP_TYPE_GET_PROPERTY_BY_LOCALS: case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: // case EXP_TYPE_GET_PROPERTY_DIM: case EXP_TYPE_INDIRECT: // case EXP_TYPE_GET_ENV_VAR_DIM: case EXP_TYPE_TAIL_CALL: // ret values are not used for tail call case EXP_TYPE_TAIL_CALL_METHOD: // ret values are not used for tail call exp->ret_values = ret_values; return exp; case EXP_TYPE_CODE_LIST: if(exp->list.count > 0){ Expression * last_exp = exp->list[exp->list.count-1]; switch(last_exp->type){ case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: case EXP_TYPE_CALL_DIM: // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: case EXP_TYPE_GET_PROPERTY: case EXP_TYPE_GET_PROPERTY_BY_LOCALS: case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: // case EXP_TYPE_GET_PROPERTY_DIM: case EXP_TYPE_INDIRECT: // case EXP_TYPE_GET_ENV_VAR_DIM: case EXP_TYPE_TAIL_CALL: // ret values are not used for tail call case EXP_TYPE_TAIL_CALL_METHOD: // ret values are not used for tail call last_exp->ret_values = ret_values; exp->ret_values = ret_values; return exp; case EXP_TYPE_RETURN: last_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, last_exp->token, last_exp OS_DBG_FILEPOS); exp->list[exp->list.count-1] = last_exp; last_exp->ret_values = ret_values; exp->ret_values = ret_values; return exp; } } break; case EXP_TYPE_RETURN: exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = ret_values; return exp; case EXP_TYPE_PARAMS: if(exp->ret_values > ret_values){ for(int i = exp->list.count-1; exp->ret_values > ret_values && i >= 0; i--){ Expression * param_exp = exp->list[i]; if(param_exp->type == EXP_TYPE_PARAMS){ break; } OS_ASSERT(param_exp->type != EXP_TYPE_PARAMS); OS_ASSERT(param_exp->type != EXP_TYPE_RETURN); OS_ASSERT(param_exp->type != EXP_TYPE_CODE_LIST); if(param_exp->isConstValue()){ exp->list.removeIndex(i); exp->ret_values--; allocator->deleteObj(param_exp); continue; } switch(param_exp->type){ case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: case EXP_TYPE_CALL_DIM: // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: case EXP_TYPE_GET_PROPERTY: case EXP_TYPE_GET_PROPERTY_BY_LOCALS: case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: // case EXP_TYPE_GET_PROPERTY_DIM: // case EXP_TYPE_GET_ENV_VAR_DIM: case EXP_TYPE_INDIRECT: if(exp->ret_values <= param_exp->ret_values){ param_exp->ret_values -= exp->ret_values; exp->ret_values = 0; }else{ exp->ret_values -= param_exp->ret_values; param_exp->ret_values = 0; } continue; } break; } } break; case EXP_TYPE_PRE_INC: case EXP_TYPE_PRE_DEC: case EXP_TYPE_POST_INC: case EXP_TYPE_POST_DEC: OS_ASSERT(exp->ret_values == 1); if(!ret_values){ exp->ret_values = 0; return exp; } break; } while(exp->ret_values > ret_values){ int new_ret_values = exp->ret_values-1; exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_POP_VALUE, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = new_ret_values; } if(exp->ret_values < ret_values){ if(exp->type != EXP_TYPE_PARAMS){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = exp->list[0]->ret_values; } while(exp->ret_values < ret_values){ Expression * null_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NULL, exp->token); null_exp->ret_values = 1; exp->list.add(null_exp OS_DBG_FILEPOS); exp->ret_values++; } } return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::newSingleValueExpression(Expression * exp) { exp = expectExpressionValues(exp, 1); switch(exp->type){ case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: case EXP_TYPE_CALL_DIM: // case EXP_TYPE_GET_DIM: case EXP_TYPE_CALL_METHOD: case EXP_TYPE_GET_PROPERTY: case EXP_TYPE_GET_PROPERTY_BY_LOCALS: case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: // case EXP_TYPE_GET_PROPERTY_DIM: // case EXP_TYPE_GET_ENV_VAR_DIM: case EXP_TYPE_INDIRECT: { exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_VALUE, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = 1; break; } } return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::newExpressionFromList(ExpressionList& list, int ret_values) { Expression * exp; if(list.count == 1){ exp = list[0]; list.removeIndex(0); }else if(list.count == 0){ TokenData * cur_token = ungetToken(); readToken(); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, cur_token); }else{ int i; for(i = 0; i < list.count-1; i++){ OS_ASSERT(list[i]->type != EXP_TYPE_CODE_LIST); list[i] = expectExpressionValues(list[i], 0); } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, list[0]->token); exp->list.swap(list); exp->ret_values = exp->list[exp->list.count-1]->ret_values; } return expectExpressionValues(exp, ret_values); } OS::Core::Compiler::Expression * OS::Core::Compiler::stepPass2(Scope * scope, Expression * exp) { switch(exp->type){ case EXP_TYPE_FUNCTION: { Scope * new_scope = dynamic_cast<Scope*>(exp); OS_ASSERT(new_scope && (new_scope->parent == scope || (!new_scope->parent && new_scope->type == EXP_TYPE_FUNCTION))); if(new_scope != scope){ new_scope->func_index = scope->function->num_local_funcs++; new_scope->func_depth = scope->function->func_depth + 1; } scope = new_scope; OS_ASSERT(prog_functions.indexOf(scope) < 0); scope->prog_func_index = prog_functions.count; allocator->vectorAddItem(prog_functions, scope OS_DBG_FILEPOS); break; } case EXP_TYPE_SCOPE: case EXP_TYPE_LOOP_SCOPE: { Scope * new_scope = dynamic_cast<Scope*>(exp); OS_ASSERT(new_scope && (new_scope->parent == scope || (!new_scope->parent && new_scope->type == EXP_TYPE_FUNCTION))); scope = new_scope; break; } case EXP_TYPE_DEBUG_LOCALS: if(exp->list.count == 0){ Expression * obj_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT, exp->token); Vector<String> vars; // skip globals & env vars allocator->vectorAddItem(vars, allocator->core->strings->var_env OS_DBG_FILEPOS); #ifdef OS_GLOBAL_VAR_ENABLED allocator->vectorAddItem(vars, allocator->core->strings->var_globals OS_DBG_FILEPOS); #endif Scope * start_scope = scope; for(; scope; scope = scope->parent){ for(int i = scope->locals.count-1; i >= 0; i--){ const Scope::LocalVar& local_var = scope->locals[i]; if(local_var.name.toChar()[0] == OS_TEXT('#')){ continue; } bool found = false; for(int j = 0; j < vars.count; j++){ if(vars[j] == local_var.name){ found = true; break; } } if(found){ continue; } allocator->vectorAddItem(vars, local_var.name OS_DBG_FILEPOS); TokenData * name_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), local_var.name, Tokenizer::NAME, exp->token->line, exp->token->pos); Expression * var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, name_token); OS_ASSERT(scope->function); var_exp->active_locals = scope->function->num_locals; var_exp->ret_values = 1; found = findLocalVar(var_exp->local_var, start_scope, local_var.name, start_scope->function->num_locals, true); OS_ASSERT(found); // && var_exp->local_var.index == local_var.index); if(start_scope->function->max_up_count < var_exp->local_var.up_count){ start_scope->function->max_up_count = var_exp->local_var.up_count; } Expression * obj_item_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT_SET_BY_NAME, name_token, var_exp OS_DBG_FILEPOS); allocator->vectorInsertAtIndex(obj_exp->list, 0, obj_item_exp OS_DBG_FILEPOS); name_token->release(); } } allocator->vectorClear(vars); obj_exp->ret_values = 1; scope = start_scope; exp->list.add(obj_exp OS_DBG_FILEPOS); } break; case EXP_TYPE_PARAMS: { for(int i = exp->list.count-1; i >= 0; i--){ Expression * sub_exp = stepPass2(scope, exp->list[i]); if(sub_exp->type == EXP_TYPE_PARAMS){ // OS_ASSERT(false); ExpressionList list(allocator); int j; for(j = 0; j < i; j++){ list.add(exp->list[j] OS_DBG_FILEPOS); } for(j = 0; j < sub_exp->list.count; j++){ list.add(sub_exp->list[j] OS_DBG_FILEPOS); } for(j = i+1; j < exp->list.count; j++){ list.add(exp->list[j] OS_DBG_FILEPOS); } exp->ret_values += sub_exp->ret_values; list.swap(exp->list); allocator->vectorClear(list); allocator->vectorClear(sub_exp->list); allocator->deleteObj(sub_exp); }else{ exp->list[i] = sub_exp; } } return exp; } case EXP_TYPE_POST_INC: case EXP_TYPE_POST_DEC: OS_ASSERT(exp->list.count == 1); if(exp->ret_values > 0){ OS_ASSERT(exp->ret_values == 1); exp->list[0] = stepPass2(scope, exp->list[0]); Expression * var_exp = exp->list[0]; OS_ASSERT(var_exp->type == EXP_TYPE_GET_LOCAL_VAR); String temp_var_name = String(allocator, OS_TEXT("#temp")); // + String(allocator, (OS_INT)scope->function->num_locals+1); TokenData * temp_var_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), temp_var_name, Tokenizer::NAME, exp->token->line, exp->token->pos); TokenData * num_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), String(allocator, OS_TEXT("1")), Tokenizer::NUMBER, exp->token->line, exp->token->pos); num_token->setFloat(1); Expression * cur_var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, var_exp->token); cur_var_exp->ret_values = 1; cur_var_exp->local_var = var_exp->local_var; Expression * result_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, exp->token); Expression * copy_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_SET_LOCAL_VAR, temp_var_token, cur_var_exp OS_DBG_FILEPOS); OS_ASSERT(!findLocalVar(copy_exp->local_var, scope, temp_var_name, scope->function->num_locals, false)); scope->addLocalVar(temp_var_name, copy_exp->local_var); result_exp->list.add(copy_exp OS_DBG_FILEPOS); cur_var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, var_exp->token); cur_var_exp->ret_values = 1; cur_var_exp->local_var = var_exp->local_var; Expression * num_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NUMBER, num_token); num_exp->ret_values = 1; Expression * op_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp->type == EXP_TYPE_POST_INC ? EXP_TYPE_ADD : EXP_TYPE_SUB, exp->token, cur_var_exp, num_exp OS_DBG_FILEPOS); op_exp->ret_values = 1; Expression * set_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_SET_LOCAL_VAR, var_exp->token, op_exp OS_DBG_FILEPOS); set_exp->local_var = var_exp->local_var; result_exp->list.add(set_exp OS_DBG_FILEPOS); Expression * get_temp_var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, temp_var_token); get_temp_var_exp->ret_values = 1; get_temp_var_exp->local_var = copy_exp->local_var; result_exp->list.add(get_temp_var_exp OS_DBG_FILEPOS); result_exp->ret_values = 1; temp_var_token->release(); num_token->release(); allocator->deleteObj(exp); return stepPass2(scope, result_exp); } exp->type = exp->type == EXP_TYPE_POST_INC ? EXP_TYPE_PRE_INC : EXP_TYPE_PRE_DEC; // no break case EXP_TYPE_PRE_INC: case EXP_TYPE_PRE_DEC: { OS_ASSERT(exp->list.count == 1); exp->list[0] = stepPass2(scope, exp->list[0]); Expression * var_exp = exp->list[0]; OS_ASSERT(var_exp->type == EXP_TYPE_GET_LOCAL_VAR); TokenData * num_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), String(allocator, OS_TEXT("1")), Tokenizer::NUMBER, exp->token->line, exp->token->pos); num_token->setFloat(1); Expression * cur_var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, var_exp->token); cur_var_exp->ret_values = 1; cur_var_exp->local_var = var_exp->local_var; Expression * num_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NUMBER, num_token); num_exp->ret_values = 1; Expression * op_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp->type == EXP_TYPE_PRE_INC ? EXP_TYPE_ADD : EXP_TYPE_SUB, exp->token, cur_var_exp, num_exp OS_DBG_FILEPOS); op_exp->ret_values = 1; Expression * set_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_SET_LOCAL_VAR, var_exp->token, op_exp OS_DBG_FILEPOS); set_exp->local_var = var_exp->local_var; Expression * result_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CODE_LIST, exp->token); result_exp->list.add(set_exp OS_DBG_FILEPOS); if(exp->ret_values > 0){ OS_ASSERT(exp->ret_values == 1); cur_var_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, var_exp->token); cur_var_exp->ret_values = 1; cur_var_exp->local_var = var_exp->local_var; result_exp->list.add(cur_var_exp OS_DBG_FILEPOS); result_exp->ret_values = 1; } allocator->deleteObj(exp); num_token->release(); return stepPass2(scope, result_exp); } case EXP_TYPE_NAME: if(findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, true)){ exp->type = EXP_TYPE_GET_LOCAL_VAR; if(scope->function->max_up_count < exp->local_var.up_count){ scope->function->max_up_count = exp->local_var.up_count; } }else{ exp->type = EXP_TYPE_GET_ENV_VAR; } break; case EXP_TYPE_RETURN: if(exp->list.count == 1){ Expression * sub_exp = exp->list[0] = stepPass2(scope, exp->list[0]); switch(sub_exp->type){ case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: sub_exp->type = EXP_TYPE_TAIL_CALL; allocator->vectorClear(exp->list); allocator->deleteObj(exp); return sub_exp; case EXP_TYPE_CALL_METHOD: sub_exp->type = EXP_TYPE_TAIL_CALL_METHOD; allocator->vectorClear(exp->list); allocator->deleteObj(exp); return sub_exp; } return exp; } break; case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: { OS_ASSERT(exp->list.count == 2); exp->list[0] = stepPass2(scope, exp->list[0]); exp->list[1] = stepPass2(scope, exp->list[1]); Expression * left_exp = exp->list[0]; Expression * right_exp = exp->list[1]; if(left_exp->type == EXP_TYPE_GET_PROPERTY){ OS_ASSERT(left_exp->list.count == 2); OS_ASSERT(right_exp->type == EXP_TYPE_PARAMS); allocator->vectorInsertAtIndex(right_exp->list, 0, left_exp->list[1] OS_DBG_FILEPOS); right_exp->ret_values += left_exp->list[1]->ret_values; left_exp->list[1] = right_exp; left_exp->type = EXP_TYPE_CALL_METHOD; left_exp->ret_values = exp->ret_values; allocator->vectorClear(exp->list); allocator->deleteObj(exp); return left_exp; } if(left_exp->type == EXP_TYPE_GET_ENV_VAR){ OS_ASSERT(left_exp->list.count == 0); OS_ASSERT(right_exp->type == EXP_TYPE_PARAMS); left_exp->type = EXP_TYPE_CONST_STRING; allocator->vectorInsertAtIndex(right_exp->list, 0, left_exp OS_DBG_FILEPOS); right_exp->ret_values++; TokenData * name_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), allocator->core->strings->var_env, Tokenizer::NAME, left_exp->token->line, left_exp->token->pos); left_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, name_token); left_exp->ret_values = 1; if(!findLocalVar(left_exp->local_var, scope, name_token->str, scope->function->num_params+ENV_VAR_INDEX+1, true)){ OS_ASSERT(false); }; if(scope->function->max_up_count < left_exp->local_var.up_count){ scope->function->max_up_count = left_exp->local_var.up_count; } exp->list[0] = left_exp; name_token->release(); exp->type = EXP_TYPE_CALL_METHOD; return exp; } /* if(left_exp->type == EXP_TYPE_GET_DIM){ OS_ASSERT(left_exp->list.count == 2); OS_ASSERT(right_exp->type == EXP_TYPE_PARAMS); if(left_exp->list[1]->list.count == 1){ Expression * params = left_exp->list[1]; OS_ASSERT(params->type == EXP_TYPE_PARAMS); allocator->vectorInsertAtIndex(right_exp->list, 0, params->list[0]); right_exp->ret_values += params->ret_values; left_exp->list[1] = right_exp; left_exp->type = EXP_TYPE_CALL_METHOD; left_exp->ret_values = exp->ret_values; allocator->vectorClear(params->list); allocator->deleteObj(params); allocator->vectorClear(exp->list); allocator->deleteObj(exp); return left_exp; } } */ return exp; } case EXP_TYPE_SET_DIM: { OS_ASSERT(exp->list.count == 3); exp->list[0] = stepPass2(scope, exp->list[0]); exp->list[1] = stepPass2(scope, exp->list[1]); exp->list[2] = stepPass2(scope, exp->list[2]); Expression * params = exp->list[2]; if(params->list.count == 1){ exp->list[2] = params->list[0]; allocator->vectorClear(params->list); allocator->deleteObj(params); exp->type = EXP_TYPE_SET_PROPERTY; for(Expression * get_exp = exp->list[1];;){ switch(get_exp->type){ case EXP_TYPE_GET_PROPERTY: OS_ASSERT(get_exp->list.count == 2); get_exp->type = EXP_TYPE_GET_PROPERTY_AUTO_CREATE; get_exp = get_exp->list[0]; continue; case EXP_TYPE_GET_LOCAL_VAR: get_exp->type = EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE; break; case EXP_TYPE_GET_ENV_VAR: get_exp->type = EXP_TYPE_GET_ENV_VAR_AUTO_CREATE; break; } break; } return exp; } if(params->list.count == 0){ // nop } break; } case EXP_TYPE_SET_PROPERTY: { OS_ASSERT(exp->list.count == 3); exp->list[0] = stepPass2(scope, exp->list[0]); exp->list[1] = stepPass2(scope, exp->list[1]); exp->list[2] = stepPass2(scope, exp->list[2]); for(Expression * get_exp = exp->list[1];;){ switch(get_exp->type){ case EXP_TYPE_GET_PROPERTY: OS_ASSERT(get_exp->list.count == 2); get_exp->type = EXP_TYPE_GET_PROPERTY_AUTO_CREATE; get_exp = get_exp->list[0]; continue; case EXP_TYPE_GET_LOCAL_VAR: get_exp->type = EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE; break; case EXP_TYPE_GET_ENV_VAR: get_exp->type = EXP_TYPE_GET_ENV_VAR_AUTO_CREATE; break; } break; } return exp; } case EXP_TYPE_CALL_DIM: { OS_ASSERT(exp->list.count == 2); exp->list[0] = stepPass2(scope, exp->list[0]); exp->list[1] = stepPass2(scope, exp->list[1]); Expression * name_exp = exp->list[0]; Expression * params = exp->list[1]; OS_ASSERT(params->type == EXP_TYPE_PARAMS); if(params->list.count == 1){ exp->list[1] = params->list[0]; allocator->vectorClear(params->list); allocator->deleteObj(params); exp->type = EXP_TYPE_GET_PROPERTY; }else{ // exp->type = EXP_TYPE_GET_DIM; String method_name = !params->list.count ? allocator->core->strings->__getempty : allocator->core->strings->__getdim; TokenData * token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), method_name, Tokenizer::NAME, name_exp->token->line, name_exp->token->pos); Expression * exp_method_name = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_STRING, token); exp_method_name->ret_values = 1; token->release(); allocator->vectorInsertAtIndex(params->list, 0, exp_method_name OS_DBG_FILEPOS); params->ret_values++; exp->type = EXP_TYPE_CALL_METHOD; } return exp; } case EXP_TYPE_INDIRECT: { OS_ASSERT(exp->list.count == 2); exp->list[0] = expectExpressionValues(exp->list[0], 1); exp->list[1] = expectExpressionValues(exp->list[1], 1); Expression * left_exp = exp->list[0]; Expression * right_exp = exp->list[1]; ExpressionType exp_type = EXP_TYPE_GET_PROPERTY; switch(right_exp->type){ case EXP_TYPE_NAME: right_exp->type = EXP_TYPE_CONST_STRING; break; case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: right_exp->type = EXP_TYPE_PARAMS; exp_type = EXP_TYPE_CALL_METHOD; OS_ASSERT(right_exp->list.count == 2); if(right_exp->list[0]->type == EXP_TYPE_NAME){ OS_ASSERT(right_exp->list[0]->ret_values == 1); right_exp->list[0]->type = EXP_TYPE_CONST_STRING; } break; } exp->type = exp_type; break; } } for(int i = 0; i < exp->list.count; i++){ exp->list[i] = stepPass2(scope, exp->list[i]); } return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::postProcessExpression(Scope * scope, Expression * exp) { exp = stepPass2(scope, exp); #if 0 return exp; #else OS_ASSERT(scope->type == EXP_TYPE_FUNCTION); // prog_stack_size = 0; return stepPass3(scope, exp); #endif } #if 1 OS::Core::Compiler::Expression * OS::Core::Compiler::stepPass3(Scope * scope, Expression * exp) { struct Lib { static Expression * processExpList(Compiler * compiler, Scope * scope, Expression * exp) { for(int i = 0; i < exp->list.count; i++){ exp->list[i] = compiler->stepPass3(scope, exp->list[i]); } return exp; } }; Expression * exp1, * exp2; switch(exp->type){ case EXP_TYPE_FUNCTION: { Scope * new_scope = dynamic_cast<Scope*>(exp); OS_ASSERT(new_scope && (new_scope->parent == scope || (!new_scope->parent && new_scope->type == EXP_TYPE_FUNCTION))); scope = new_scope; break; } case EXP_TYPE_SCOPE: case EXP_TYPE_LOOP_SCOPE: { Scope * new_scope = dynamic_cast<Scope*>(exp); OS_ASSERT(new_scope && (new_scope->parent == scope || (!new_scope->parent && new_scope->type == EXP_TYPE_FUNCTION))); scope = new_scope; break; } case EXP_TYPE_GET_PROPERTY: { OS_ASSERT(exp->list.count == 2); exp = Lib::processExpList(this, scope, exp); exp1 = exp->list[0]; exp2 = exp->list[1]; if(exp1->type == EXP_TYPE_GET_LOCAL_VAR && exp2->type == EXP_TYPE_GET_LOCAL_VAR && !exp1->local_var.up_count && exp1->local_var.index <= 255 && !exp2->local_var.up_count && exp2->local_var.index <= 255) { exp->type = EXP_TYPE_GET_PROPERTY_BY_LOCALS; }else if(exp1->type == EXP_TYPE_GET_LOCAL_VAR && exp2->type == EXP_TYPE_CONST_NUMBER && !exp1->local_var.up_count && exp1->local_var.index <= 255) { exp->type = EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER; } return exp; } case EXP_TYPE_SET_PROPERTY: { OS_ASSERT(exp->list.count == 3); exp = Lib::processExpList(this, scope, exp); exp1 = exp->list[1]; exp2 = exp->list[2]; if(exp1->type == EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE && exp2->type == EXP_TYPE_GET_LOCAL_VAR && !exp1->local_var.up_count && exp1->local_var.index <= 255 && !exp2->local_var.up_count && exp2->local_var.index <= 255) { if(exp->list[0]->type == EXP_TYPE_GET_PROPERTY_BY_LOCALS){ exp->type = EXP_TYPE_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE; }else{ exp->type = EXP_TYPE_SET_PROPERTY_BY_LOCALS_AUTO_CREATE; } } return exp; } case EXP_TYPE_CONCAT: case EXP_TYPE_LOGIC_PTR_EQ: case EXP_TYPE_LOGIC_PTR_NE: case EXP_TYPE_LOGIC_EQ: case EXP_TYPE_LOGIC_NE: case EXP_TYPE_LOGIC_GE: case EXP_TYPE_LOGIC_LE: case EXP_TYPE_LOGIC_GREATER: case EXP_TYPE_LOGIC_LESS: case EXP_TYPE_BIT_AND: case EXP_TYPE_BIT_OR: case EXP_TYPE_BIT_XOR: case EXP_TYPE_ADD: // + case EXP_TYPE_SUB: // - case EXP_TYPE_MUL: // * case EXP_TYPE_DIV: // / case EXP_TYPE_MOD: // % case EXP_TYPE_LSHIFT: // << case EXP_TYPE_RSHIFT: // >> case EXP_TYPE_POW: // ** { OS_ASSERT(exp->list.count == 2); exp = Lib::processExpList(this, scope, exp); exp1 = exp->list[0]; exp2 = exp->list[1]; if(exp1->type == EXP_TYPE_GET_LOCAL_VAR && exp2->type == EXP_TYPE_GET_LOCAL_VAR && !exp1->local_var.up_count && exp1->local_var.index <= 255 && !exp2->local_var.up_count && exp2->local_var.index <= 255) { exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_BIN_OPERATOR_BY_LOCALS, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = exp->list[0]->ret_values; }else if(exp1->type == EXP_TYPE_GET_LOCAL_VAR && exp2->type == EXP_TYPE_CONST_NUMBER && !exp1->local_var.up_count && exp1->local_var.index <= 255) { exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = exp->list[0]->ret_values; } return exp; } case EXP_TYPE_SET_LOCAL_VAR: { OS_ASSERT(exp->list.count == 1); exp = Lib::processExpList(this, scope, exp); if(!exp->local_var.up_count && exp->local_var.index <= 255){ exp1 = exp->list[0]; if(exp1->type == EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER){ exp->type = EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER; }else if(exp1->type == EXP_TYPE_BIN_OPERATOR_BY_LOCALS){ exp->type = EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS; } } return exp; } case EXP_TYPE_POST_INC: case EXP_TYPE_POST_DEC: case EXP_TYPE_PRE_INC: case EXP_TYPE_PRE_DEC: OS_ASSERT(false); break; case EXP_TYPE_NAME: OS_ASSERT(false); break; case EXP_TYPE_CALL_DIM: OS_ASSERT(false); break; case EXP_TYPE_INDIRECT: OS_ASSERT(false); break; } return Lib::processExpList(this, scope, exp); } #endif OS::Core::Compiler::Scope * OS::Core::Compiler::expectTextExpression() { OS_ASSERT(recent_token); Scope * scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(NULL, EXP_TYPE_FUNCTION, recent_token); // scope->function = scope; scope->parser_started = true; scope->ret_values = 1; scope->addStdVars(); Params p = Params() .setAllowAssign(true) .setAllowAutoCall(true) .setAllowBinaryOperator(true) .setAllowParams(true) .setAllowRootBlocks(true); Expression * exp; ExpressionList list(allocator); while(!isError()){ exp = expectSingleExpression(scope, p); if(isError()){ break; } if(exp){ list.add(exp OS_DBG_FILEPOS); } if(!recent_token){ break; } TokenType token_type = recent_token->type; if(token_type == Tokenizer::CODE_SEPARATOR){ if(!readToken()){ break; } token_type = recent_token->type; } if(token_type == Tokenizer::END_ARRAY_BLOCK || token_type == Tokenizer::END_BRACKET_BLOCK || token_type == Tokenizer::END_CODE_BLOCK) { break; } } if(isError()){ allocator->deleteObj(scope); return NULL; } if(recent_token){ setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(scope); return NULL; } if(list.count == 0){ return scope; } int ret_values = list.count == 1 && list[0]->ret_values > 0 && list[0]->type == EXP_TYPE_FUNCTION ? 1 : 0; { putNextTokenType(Tokenizer::CODE_SEPARATOR); readToken(); TokenData * name_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), allocator->core->strings->var_env, Tokenizer::NAME, recent_token->line, recent_token->pos); ExpressionList& func_exp_list = ret_values == 1 ? list[0]->list : list; Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, name_token); name_exp->ret_values = 1; if(!findLocalVar(name_exp->local_var, scope, allocator->core->strings->var_env, scope->num_locals, false)){ OS_ASSERT(false); } OS_ASSERT(name_exp->local_var.up_count == 0); Expression * ret_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_RETURN, recent_token, name_exp OS_DBG_FILEPOS); ret_exp->ret_values = 1; func_exp_list.add(ret_exp OS_DBG_FILEPOS); name_token->release(); } exp = newExpressionFromList(list, ret_values); switch(exp->type){ case EXP_TYPE_CODE_LIST: if(exp->list.count == 1 && exp->list[0]->type == EXP_TYPE_FUNCTION){ allocator->deleteObj(scope); scope = dynamic_cast<Scope*>(exp->list[0]); allocator->vectorClear(exp->list); allocator->deleteObj(exp); return scope; } // exp = expectExpressionValues(exp, 0); scope->list.swap(exp->list); allocator->deleteObj(exp); break; case EXP_TYPE_FUNCTION: OS_ASSERT(scope->num_locals == 0); allocator->deleteObj(scope); scope = dynamic_cast<Scope*>(exp); OS_ASSERT(scope); scope->parent = NULL; return scope; default: scope->list.add(exp OS_DBG_FILEPOS); } return scope; } OS::Core::Compiler::Scope * OS::Core::Compiler::expectCodeExpression(Scope * parent, int ret_values) { OS_ASSERT(recent_token && recent_token->type == Tokenizer::BEGIN_CODE_BLOCK); if(!expectToken()){ allocator->deleteObj(parent); return NULL; } Scope * scope; // bool is_new_func; if(parent->type == EXP_TYPE_FUNCTION && !parent->parser_started){ scope = parent; // is_new_func = true; parent->parser_started = true; }else{ scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(parent, EXP_TYPE_SCOPE, recent_token); // scope->function = parent->function; // is_new_func = false; } Params p = Params() .setAllowAssign(true) .setAllowAutoCall(true) .setAllowBinaryOperator(true) .setAllowParams(true) .setAllowRootBlocks(true); Expression * exp; ExpressionList list(allocator); while(!isError()){ exp = expectSingleExpression(scope, p); if(isError()){ break; } if(exp){ list.add(exp OS_DBG_FILEPOS); } TokenType token_type = recent_token->type; if(token_type == Tokenizer::CODE_SEPARATOR){ if(!readToken()){ break; } token_type = recent_token->type; } if(token_type == Tokenizer::END_ARRAY_BLOCK || token_type == Tokenizer::END_BRACKET_BLOCK || token_type == Tokenizer::END_CODE_BLOCK) { break; } } if(isError()){ allocator->deleteObj(scope); return NULL; } if(!recent_token || recent_token->type != Tokenizer::END_CODE_BLOCK){ setError(Tokenizer::END_CODE_BLOCK, recent_token); allocator->deleteObj(scope); return NULL; } readToken(); if(list.count == 0){ return scope; } exp = newExpressionFromList(list, ret_values); switch(exp->type){ case EXP_TYPE_CODE_LIST: { scope->list.swap(exp->list); allocator->deleteObj(exp); break; } // no break default: scope->list.add(exp OS_DBG_FILEPOS); } return scope; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectObjectExpression(Scope * scope, const Params& org_p, bool allow_finish_exp) { OS_ASSERT(recent_token && recent_token->type == Tokenizer::BEGIN_CODE_BLOCK); struct Lib { Compiler * compiler; Expression * obj_exp; Expression * finishValue(Scope * scope, const Params& p, bool allow_finish_exp) { if(!allow_finish_exp){ return obj_exp; } return compiler->finishValueExpression(scope, obj_exp, Params(p).setAllowAssign(false).setAllowAutoCall(false)); } void * malloc(int size OS_DBG_FILEPOS_DECL) { return compiler->malloc(size OS_DBG_FILEPOS_PARAM); } Lib(Compiler * p_compiler, int active_locals) { compiler = p_compiler; obj_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT, compiler->recent_token); obj_exp->ret_values = 1; } Expression * error() { compiler->allocator->deleteObj(obj_exp); return NULL; } Expression * error(ErrorType err, TokenData * token) { compiler->setError(err, token); return error(); } Expression * error(TokenType err, TokenData * token) { compiler->setError(err, token); return error(); } } lib(this, scope->function->num_locals); Params p = Params().setAllowBinaryOperator(true); // TokenData * name_token, * save_token; for(readToken();;){ Expression * exp = NULL; if(!recent_token){ return lib.error(ERROR_SYNTAX, recent_token); } if(recent_token->type == Tokenizer::END_CODE_BLOCK){ readToken(); return lib.finishValue(scope, org_p, allow_finish_exp); } TokenData * name_token = recent_token; if(name_token->type == Tokenizer::BEGIN_ARRAY_BLOCK){ readToken(); TokenData * save_token = recent_token; exp = expectSingleExpression(scope, p); if(!exp){ return lib.error(); } if(exp->ret_values < 1){ allocator->deleteObj(exp); return lib.error(ERROR_EXPECT_VALUE, save_token); } exp = expectExpressionValues(exp, 1); if(!recent_token || recent_token->type != Tokenizer::END_ARRAY_BLOCK){ allocator->deleteObj(exp); return lib.error(Tokenizer::END_ARRAY_BLOCK, recent_token); } if(!readToken() || (recent_token->type != Tokenizer::OPERATOR_COLON && recent_token->type != Tokenizer::OPERATOR_ASSIGN)){ allocator->deleteObj(exp); return lib.error(Tokenizer::OPERATOR_COLON, recent_token); } save_token = readToken(); Expression * exp2 = expectSingleExpression(scope, p); if(!exp2){ return isError() ? lib.error() : lib.error(ERROR_EXPECT_EXPRESSION, save_token); } exp2 = expectExpressionValues(exp2, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT_SET_BY_EXP, name_token, exp, exp2 OS_DBG_FILEPOS); }else if(isNextToken(Tokenizer::OPERATOR_COLON) || isNextToken(Tokenizer::OPERATOR_ASSIGN)){ ExpressionType exp_type = EXP_TYPE_OBJECT_SET_BY_NAME; switch(name_token->type){ case Tokenizer::STRING: case Tokenizer::NAME: break; case Tokenizer::NUMBER: if(name_token->getFloat() != (OS_FLOAT)(OS_INT)name_token->getFloat()){ // use it as EXP_TYPE_OBJECT_SET_BY_NAME break; } exp_type = EXP_TYPE_OBJECT_SET_BY_INDEX; break; default: return lib.error(ERROR_SYNTAX, name_token); } readToken(); // skip OPERATOR_COLON TokenData * save_token = readToken(); exp = expectSingleExpression(scope, p); if(!exp){ return isError() ? lib.error() : lib.error(ERROR_EXPECT_EXPRESSION, save_token); } exp = expectExpressionValues(exp, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp_type, name_token, exp OS_DBG_FILEPOS); }else{ exp = expectSingleExpression(scope, p); if(!exp){ return isError() ? lib.error() : lib.error(ERROR_EXPECT_EXPRESSION, name_token); } exp = expectExpressionValues(exp, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT_SET_BY_AUTO_INDEX, name_token, exp OS_DBG_FILEPOS); } OS_ASSERT(exp); lib.obj_exp->list.add(exp OS_DBG_FILEPOS); if(recent_token && recent_token->type == Tokenizer::END_CODE_BLOCK){ readToken(); return lib.finishValue(scope, org_p, allow_finish_exp); } #if 11 if(!recent_token){ return lib.error(Tokenizer::END_CODE_BLOCK, recent_token); } switch(recent_token->type){ case Tokenizer::PARAM_SEPARATOR: case Tokenizer::CODE_SEPARATOR: readToken(); } #else if(!recent_token || (recent_token->type != Tokenizer::PARAM_SEPARATOR && recent_token->type != Tokenizer::CODE_SEPARATOR)){ return lib.error(Tokenizer::PARAM_SEPARATOR, recent_token); } readToken(); #endif } return NULL; // shut up compiler } OS::Core::Compiler::Expression * OS::Core::Compiler::expectArrayExpression(Scope * scope, const Params& __p) { Params next_p = Params(__p).setAllowAssign(false).setAllowAutoCall(false); Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_ARRAY, recent_token); params->ret_values = 1; readToken(); if(recent_token && recent_token->type == Tokenizer::END_ARRAY_BLOCK){ readToken(); return finishValueExpression(scope, params, next_p); } Params p = Params().setAllowBinaryOperator(true); for(;;){ Expression * exp = expectSingleExpression(scope, p); if(!exp){ if(isError()){ allocator->deleteObj(params); return NULL; } if(!recent_token || recent_token->type != Tokenizer::END_ARRAY_BLOCK){ setError(Tokenizer::END_ARRAY_BLOCK, recent_token); allocator->deleteObj(params); return NULL; } readToken(); return finishValueExpression(scope, params, next_p); } exp = expectExpressionValues(exp, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_OBJECT_SET_BY_AUTO_INDEX, exp->token, exp OS_DBG_FILEPOS); params->list.add(exp OS_DBG_FILEPOS); if(recent_token && recent_token->type == Tokenizer::END_ARRAY_BLOCK){ readToken(); return finishValueExpression(scope, params, next_p); } #if 11 if(!recent_token){ setError(Tokenizer::END_ARRAY_BLOCK, recent_token); allocator->deleteObj(params); return NULL; } switch(recent_token->type){ case Tokenizer::PARAM_SEPARATOR: case Tokenizer::CODE_SEPARATOR: readToken(); } #else if(!recent_token || (recent_token->type != Tokenizer::PARAM_SEPARATOR && recent_token->type != Tokenizer::CODE_SEPARATOR)){ setError(Tokenizer::PARAM_SEPARATOR, recent_token); allocator->deleteObj(params); return NULL; } readToken(); #endif } return NULL; // shut up compiler } OS::Core::Compiler::Expression * OS::Core::Compiler::expectParamsExpression(Scope * scope) { struct Lib { static Expression * calcParamsExpression(Compiler * compiler, Scope * scope, Expression * params) { if(params->list.count > 1){ for(int i = 0; i < params->list.count; i++){ params->list[i] = compiler->expectExpressionValues(params->list[i], 1); } params->ret_values = params->list.count; }else if(params->list.count == 1){ params->ret_values = params->list[0]->ret_values; } return params; } }; // OS_ASSERT(recent_token->type == Tokenizer::PARAM_SEPARATOR); Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, recent_token); bool is_dim = recent_token->type == Tokenizer::BEGIN_ARRAY_BLOCK; TokenType end_exp_type = is_dim ? Tokenizer::END_ARRAY_BLOCK : Tokenizer::END_BRACKET_BLOCK; readToken(); if(recent_token && recent_token->type == end_exp_type){ readToken(); return Lib::calcParamsExpression(this, scope, params); } Params p = Params().setAllowBinaryOperator(true); for(;;){ Expression * exp = expectSingleExpression(scope, p); if(!exp){ if(isError()){ allocator->deleteObj(params); return NULL; } if(!recent_token || recent_token->type != end_exp_type){ setError(end_exp_type, recent_token); allocator->deleteObj(params); return NULL; } readToken(); return Lib::calcParamsExpression(this, scope, params); } // exp = expectExpressionValues(exp, 1); params->list.add(exp OS_DBG_FILEPOS); // params->ret_values += exp->ret_values; if(recent_token && (recent_token->type == Tokenizer::PARAM_SEPARATOR || recent_token->type == Tokenizer::CODE_SEPARATOR)){ readToken(); } if(recent_token && recent_token->type == end_exp_type){ readToken(); return Lib::calcParamsExpression(this, scope, params); } if(!recent_token){ // || recent_token->type != Tokenizer::PARAM_SEPARATOR){ // setError(Tokenizer::PARAM_SEPARATOR, recent_token); setError(end_exp_type, recent_token); allocator->deleteObj(params); return NULL; } } return NULL; // shut up compiler } OS::Core::Compiler::Expression * OS::Core::Compiler::expectBracketExpression(Scope * scope, const Params& p) { OS_ASSERT(recent_token && recent_token->type == Tokenizer::BEGIN_BRACKET_BLOCK); readToken(); Expression * exp = expectSingleExpression(scope, Params() .setAllowBinaryOperator(true) .setAllowCall(true) .setAllowAutoCall(true)); if(!exp){ return NULL; } exp = newSingleValueExpression(exp); OS_ASSERT(exp->ret_values == 1); if(!recent_token){ setError(Tokenizer::END_BRACKET_BLOCK, recent_token); allocator->deleteObj(exp); return NULL; } switch(recent_token->type){ case Tokenizer::END_BRACKET_BLOCK: readToken(); return finishValueExpression(scope, exp, p); } setError(Tokenizer::END_BRACKET_BLOCK, recent_token); allocator->deleteObj(exp); return NULL; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectExtendsExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_extends); TokenData * save_token = recent_token; if(!expectToken()){ return NULL; } Params p; Expression * exp = expectSingleExpression(scope, p); if(!exp){ return NULL; } if(exp->type == EXP_TYPE_CALL_AUTO_PARAM){ OS_ASSERT(exp->list.count == 2); Expression * params = exp->list[1]; OS_ASSERT(params->type == EXP_TYPE_PARAMS && params->list.count == 1); exp->list[1] = params->list[0]; allocator->vectorClear(params->list); allocator->deleteObj(params); exp->type = EXP_TYPE_EXTENDS; exp->ret_values = 1; return exp; } Expression * exp2 = expectSingleExpression(scope, p); if(!exp2){ allocator->deleteObj(exp); return NULL; } exp = expectExpressionValues(exp, 1); exp2 = expectExpressionValues(exp2, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_EXTENDS, save_token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::finishQuestionOperator(Scope * scope, TokenData * token, Expression * exp, Expression * exp2) { // OS_ASSERT(recent_token && recent_token->type == Tokenizer::OPERATOR_COLON); ungetToken(); if(!expectToken(Tokenizer::OPERATOR_COLON)){ allocator->deleteObj(exp); allocator->deleteObj(exp2); return NULL; } if(!expectToken()){ return NULL; } Expression * exp3 = expectSingleExpression(scope, Params().setAllowBinaryOperator(true)); if(!exp3){ allocator->deleteObj(exp); allocator->deleteObj(exp2); return NULL; } exp = expectExpressionValues(exp, 1); exp2 = expectExpressionValues(exp2, 1); exp3 = expectExpressionValues(exp3, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_QUESTION, token, exp, exp2, exp3 OS_DBG_FILEPOS); exp->ret_values = 1; return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectCloneExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_clone); TokenData * save_token = recent_token; if(!expectToken()){ return NULL; } Expression * exp = expectSingleExpression(scope, Params()); if(!exp){ return NULL; } exp = expectExpressionValues(exp, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CLONE, save_token, exp OS_DBG_FILEPOS); exp->ret_values = 1; return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectDeleteExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_delete); TokenData * save_token = recent_token; if(!expectToken()){ return NULL; } Expression * exp = expectSingleExpression(scope, Params()); if(!exp){ return NULL; } if(exp->type == EXP_TYPE_INDIRECT){ OS_ASSERT(exp->list.count == 2); Expression * field = exp->list[1]; if(field->type == EXP_TYPE_NAME){ field->type = EXP_TYPE_CONST_STRING; } exp->type = EXP_TYPE_DELETE; exp->ret_values = 0; return exp; } if(exp->type == EXP_TYPE_CALL_DIM){ OS_ASSERT(exp->list.count == 2); Expression * params = exp->list[1]; if(params->list.count == 1){ exp->list[1] = params->list[0]; allocator->vectorClear(params->list); allocator->deleteObj(params); exp->type = EXP_TYPE_DELETE; exp->ret_values = 0; return exp; } Expression * object = exp->list[0]; String method_name = !params->list.count ? allocator->core->strings->__delempty : allocator->core->strings->__deldim; TokenData * token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), method_name, Tokenizer::NAME, object->token->line, object->token->pos); Expression * exp_method_name = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_STRING, token); exp_method_name->ret_values = 1; token->release(); Expression * indirect = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_INDIRECT, object->token, object, exp_method_name OS_DBG_FILEPOS); exp->list[0] = indirect; exp->type = EXP_TYPE_CALL; exp->ret_values = 1; return exp; } setError(ERROR_SYNTAX, exp->token); allocator->deleteObj(exp); return NULL; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectValueOfExpression(Scope * scope, ExpressionType exp_type) { OS_ASSERT(recent_token); TokenData * save_token = recent_token; if(!expectToken()){ return NULL; } Expression * exp = expectSingleExpression(scope, Params()); if(!exp){ return NULL; } exp = expectExpressionValues(exp, 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp_type, save_token, exp OS_DBG_FILEPOS); exp->ret_values = 1; return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectFunctionExpression(Scope * parent) { Scope * scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(parent, EXP_TYPE_FUNCTION, recent_token); scope->function = scope; scope->ret_values = 1; Expression * name_exp = NULL; if(isNextToken(Tokenizer::NAME)){ TokenData * token = readToken(); if(isNextToken(Tokenizer::NAME)){ String prefix(allocator); if(token->str == allocator->core->strings->syntax_get){ prefix = allocator->core->strings->__getAt; }else if(token->str == allocator->core->strings->syntax_set){ prefix = allocator->core->strings->__setAt; }else{ setError(ERROR_EXPECT_GET_OR_SET, token); allocator->deleteObj(name_exp); allocator->deleteObj(scope); return NULL; } token = readToken(); token->str = String(allocator, prefix, token->str); name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, token); }else{ name_exp = expectSingleExpression(parent, Params().setAllowCall(false)); if(!name_exp || !name_exp->isWriteable()){ setError(ERROR_EXPECT_WRITEABLE, token); allocator->deleteObj(name_exp); allocator->deleteObj(scope); return NULL; } ungetToken(); } } if(!expectToken(Tokenizer::BEGIN_BRACKET_BLOCK)){ allocator->deleteObj(scope); return NULL; } for(;;){ if(!readToken()){ setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(scope); return NULL; } switch(recent_token->type){ case Tokenizer::END_BRACKET_BLOCK: break; case Tokenizer::NAME: // scope->list.add(new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, recent_token)); scope->addLocalVar(recent_token->str); scope->num_params++; if(!readToken()){ setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(scope); return NULL; } if(recent_token->type == Tokenizer::END_BRACKET_BLOCK){ break; } if(recent_token->type == Tokenizer::PARAM_SEPARATOR){ continue; } #if 11 ungetToken(); continue; #else setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(scope); return NULL; #endif default: setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(scope); return NULL; } break; } OS_ASSERT(recent_token && recent_token->type == Tokenizer::END_BRACKET_BLOCK); if(!expectToken(Tokenizer::BEGIN_CODE_BLOCK)){ allocator->deleteObj(scope); return NULL; } scope->addStdVars(); scope = expectCodeExpression(scope); if(!scope || !name_exp){ return scope; } return newBinaryExpression(parent, EXP_TYPE_ASSIGN, name_exp->token, name_exp, scope); } OS::Core::Compiler::Expression * OS::Core::Compiler::expectVarExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_var); if(!expectToken(Tokenizer::NAME)){ return NULL; } Expression * name_exp; Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, recent_token); exp->ret_values = 1; if(recent_token->str == allocator->core->strings->syntax_function){ if(!expectToken(Tokenizer::NAME)){ allocator->deleteObj(exp); return NULL; } TokenData * name_token; if(recent_token->str == allocator->core->strings->syntax_get || recent_token->str == allocator->core->strings->syntax_set){ bool is_getter = recent_token->str == allocator->core->strings->syntax_get; if(!expectToken(Tokenizer::NAME)){ allocator->deleteObj(exp); return NULL; } if(!isVarNameValid(recent_token->str)){ setError(ERROR_VAR_NAME, recent_token); allocator->deleteObj(exp); return NULL; } if(!expectToken(Tokenizer::BEGIN_BRACKET_BLOCK)){ allocator->deleteObj(exp); return NULL; } ungetToken(); ungetToken(); name_token = tokenizer->removeToken(next_token_index-1); name_token->release(); name_token = tokenizer->removeToken(next_token_index-1); //name_token->str = if(is_getter){ name_token->str = String(allocator, allocator->core->strings->__getAt, name_token->str); }else{ name_token->str = String(allocator, allocator->core->strings->__setAt, name_token->str); } }else{ if(!isVarNameValid(recent_token->str)){ setError(ERROR_VAR_NAME, recent_token); allocator->deleteObj(exp); return NULL; } if(!expectToken(Tokenizer::BEGIN_BRACKET_BLOCK)){ allocator->deleteObj(exp); return NULL; } ungetToken(); name_token = tokenizer->removeToken(next_token_index-1); } name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, name_token); name_exp->ret_values = 1; name_token->release(); allocator->deleteObj(exp); // exp->list.add(name_exp OS_DBG_FILEPOS); // exp->ret_values++; ungetToken(); // return to function Expression * func_exp = expectFunctionExpression(scope); if(!func_exp){ allocator->deleteObj(exp); return NULL; } OS_ASSERT(func_exp->type == EXP_TYPE_FUNCTION); exp = newBinaryExpression(scope, EXP_TYPE_ASSIGN, name_exp->token, name_exp, func_exp); }else{ for(;;){ if(!isVarNameValid(recent_token->str)){ setError(ERROR_VAR_NAME, recent_token); allocator->deleteObj(exp); return NULL; } name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, recent_token); name_exp->ret_values = 1; exp->list.add(name_exp OS_DBG_FILEPOS); exp->ret_values++; if(!readToken() || recent_token->type != Tokenizer::PARAM_SEPARATOR){ break; } if(!expectToken(Tokenizer::NAME)){ allocator->deleteObj(exp); return NULL; } } /* while(readToken()){ if(recent_token->type != Tokenizer::PARAM_SEPARATOR){ break; } if(!expectToken(Tokenizer::NAME)){ allocator->deleteObj(exp); return NULL; } if(!isVarNameValid(recent_token->str)){ setError(ERROR_VAR_NAME, recent_token); allocator->deleteObj(exp); return NULL; } name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, recent_token); name_exp->ret_values = 1; exp->list.add(name_exp OS_DBG_FILEPOS); exp->ret_values++; } */ if(recent_token && recent_token->type == Tokenizer::OPERATOR_ASSIGN){ bool is_finished; exp = finishBinaryOperator(scope, getOpcodeLevel(exp->type), exp, Params().setAllowParams(true).setAllowInOperator(true), is_finished); OS_ASSERT(is_finished); } } // Expression * exp = expectSingleExpression(scope, Params().setAllowParams(true).setAllowAssign(true)); // false, true, false, true, false); Expression * ret_exp = exp; while(exp){ switch(exp->type){ case EXP_TYPE_PARAMS: { Expression * params = exp; for(int i = 0; i < params->list.count; i++){ exp = params->list[i]; OS_ASSERT(exp->type == EXP_TYPE_NAME); if(exp->type == EXP_TYPE_NAME){ if(findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, false)){ // setError(ERROR_VAR_ALREADY_EXIST, exp->token); // allocator->deleteObj(ret_exp); // return NULL; // OS_ASSERT(true); }else{ scope->addLocalVar(exp->token->str, exp->local_var); } OS_ASSERT(exp->local_var.up_count == 0); exp->type = EXP_TYPE_NEW_LOCAL_VAR; exp->ret_values = 0; } } params->ret_values = 0; return params; } case EXP_TYPE_SET_LOCAL_VAR: for(;;){ if(exp->local_var.up_scope_count == 0){ // setError(ERROR_VAR_ALREADY_EXIST, exp->token); // allocator->deleteObj(ret_exp); // return NULL; OS_ASSERT(true); }else{ OS_ASSERT(!findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, false)); scope->addLocalVar(exp->token->str, exp->local_var); } OS_ASSERT(exp->list.count == 1); exp = exp->list[0]; switch(exp->type){ case EXP_TYPE_SET_ENV_VAR: case EXP_TYPE_SET_LOCAL_VAR: break; default: return ret_exp; } break; } break; case EXP_TYPE_SET_ENV_VAR: for(;;){ OS_ASSERT(!findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, false)); scope->addLocalVar(exp->token->str, exp->local_var); exp->type = EXP_TYPE_SET_LOCAL_VAR; OS_ASSERT(exp->list.count == 1); exp = exp->list[0]; switch(exp->type){ case EXP_TYPE_SET_ENV_VAR: case EXP_TYPE_SET_LOCAL_VAR: break; default: return ret_exp; } break; } break; case EXP_TYPE_NAME: if(findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, false)){ // setError(ERROR_VAR_ALREADY_EXIST, exp->token); // allocator->deleteObj(ret_exp); // return NULL; OS_ASSERT(true); }else{ scope->addLocalVar(exp->token->str, exp->local_var); } OS_ASSERT(exp->local_var.up_count == 0); exp->type = EXP_TYPE_NEW_LOCAL_VAR; exp->ret_values = 0; return ret_exp; default: return ret_exp; } } return ret_exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectForExpression(Scope * parent) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_for); Scope * scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(parent, EXP_TYPE_SCOPE, recent_token); if(!expectToken(Tokenizer::BEGIN_BRACKET_BLOCK) || !expectToken()){ allocator->deleteObj(scope); return NULL; } // Expression * exp = expectSingleExpression(scope, true); // , true, true, true, true, true); Expression * exp = expectSingleExpression(scope, Params() .setAllowAssign(true) .setAllowAutoCall(true) .setAllowBinaryOperator(true) .setAllowParams(true) .setAllowVarDecl(true) .setAllowNopResult(true) .setAllowInOperator(false)); if(!exp){ allocator->deleteObj(scope); return NULL; } if(!recent_token){ setError(ERROR_EXPECT_TOKEN, recent_token); allocator->deleteObj(scope); allocator->deleteObj(exp); return NULL; } if(recent_token->type == Tokenizer::NAME && (exp->type == EXP_TYPE_PARAMS || exp->type == EXP_TYPE_NEW_LOCAL_VAR || exp->type == EXP_TYPE_NAME)){ if(recent_token->str != allocator->core->strings->syntax_in){ setError(allocator->core->strings->syntax_in, recent_token); allocator->deleteObj(scope); allocator->deleteObj(exp); return NULL; } ExpressionList vars(allocator); if(exp->type == EXP_TYPE_PARAMS){ vars.swap(exp->list); allocator->deleteObj(exp); }else{ vars.add(exp OS_DBG_FILEPOS); } exp = NULL; for(int i = 0; i < vars.count; i++){ OS_ASSERT(vars[i]->type == EXP_TYPE_NAME || vars[i]->type == EXP_TYPE_NEW_LOCAL_VAR); Expression * name_exp = vars[i]; if(name_exp->type == EXP_TYPE_NAME){ /* scope->addLocalVar(name_exp->token->str, name_exp->local_var); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->type = EXP_TYPE_NEW_LOCAL_VAR; */ name_exp->type = EXP_TYPE_NOP; } } if(!expectToken()){ allocator->deleteObj(scope); return NULL; } exp = expectSingleExpression(scope, Params().setAllowBinaryOperator(true).setAllowAutoCall(true)); // true, false, false, false, true); if(!recent_token || recent_token->type != Tokenizer::END_BRACKET_BLOCK){ setError(Tokenizer::END_BRACKET_BLOCK, recent_token); allocator->deleteObj(scope); allocator->deleteObj(exp); return NULL; } if(!exp->ret_values){ setError(ERROR_EXPECT_VALUE, exp->token); allocator->deleteObj(scope); allocator->deleteObj(exp); return NULL; } exp = expectExpressionValues(exp, 1); if(!expectToken()){ allocator->deleteObj(scope); allocator->deleteObj(exp); return NULL; } Scope * loop_scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(scope, EXP_TYPE_LOOP_SCOPE, recent_token); Expression * body_exp = expectSingleExpression(loop_scope, true, true); /* if(recent_token->type == Tokenizer::BEGIN_CODE_BLOCK){ body_exp = expectCodeExpression(loop_scope); }else{ body_exp = expectSingleExpression(loop_scope, true); } */ if(!body_exp){ allocator->deleteObj(scope); allocator->deleteObj(exp); allocator->deleteObj(loop_scope); return NULL; } body_exp = expectExpressionValues(body_exp, 0); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL_METHOD, exp->token, exp OS_DBG_FILEPOS); { Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, exp->token); String method_name = allocator->core->strings->__iter; TokenData * token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), method_name, Tokenizer::NAME, exp->token->line, exp->token->pos); Expression * exp_method_name = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_STRING, token); exp_method_name->ret_values = 1; token->release(); params->list.add(exp_method_name OS_DBG_FILEPOS); params->ret_values = 1; exp->list.add(params OS_DBG_FILEPOS); } exp = expectExpressionValues(exp, vars.count + 1); int num_locals = vars.count; // ExpressionList temp_vars(allocator); const int temp_count = 2; const OS_CHAR * temp_names[temp_count] = { OS_TEXT("#func"), /*OS_TEXT("#state"), OS_TEXT("#state2"), */ OS_TEXT("#valid") }; for(int i = 0; i < temp_count; i++){ String name(allocator, temp_names[i]); TokenData * token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), name, Tokenizer::NAME, exp->token->line, exp->token->pos); Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NEW_LOCAL_VAR, token); // name_exp->ret_values = 1; vars.add(name_exp OS_DBG_FILEPOS); token->release(); scope->addLocalVar(name, name_exp->local_var); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->local_var.type = LOCAL_TEMP; } ExpressionList list(allocator); // var func, state, state2 = (in_exp).__iter() { Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, exp->token); for(int i = num_locals; i < vars.count-1; i++){ Expression * var_exp = vars[i]; Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, var_exp->token); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->ret_values = 1; params->list.add(name_exp OS_DBG_FILEPOS); } params->ret_values = params->list.count; String assing_operator(allocator, OS_TEXT("=")); TokenData * assign_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), assing_operator, Tokenizer::OPERATOR_ASSIGN, exp->token->line, exp->token->pos); exp = newBinaryExpression(scope, EXP_TYPE_ASSIGN, assign_token, params, exp); OS_ASSERT(exp && exp->type == EXP_TYPE_SET_LOCAL_VAR && !exp->ret_values); assign_token->release(); list.add(exp OS_DBG_FILEPOS); exp = NULL; } /* begin loop var valid, k, v = func(state, state2) if(!valid) break body_exp end loop */ list.add(loop_scope OS_DBG_FILEPOS); { // var valid, k, v Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, loop_scope->token); for(int i = 0; i < num_locals+1; i++){ Expression * var_exp = !i ? vars.lastElement() : vars[i-1]; Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, var_exp->token); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->ret_values = 1; params->list.add(name_exp OS_DBG_FILEPOS); } params->ret_values = params->list.count; // func(state, state2) Expression * call_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL, loop_scope->token); { Expression * var_exp = vars[num_locals]; // func Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, var_exp->token); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->ret_values = 1; call_exp->list.add(name_exp OS_DBG_FILEPOS); Expression * params = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, loop_scope->token); for(int i = num_locals+1; i < vars.count-1; i++){ Expression * var_exp = vars[i]; Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, var_exp->token); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->ret_values = 1; params->list.add(name_exp OS_DBG_FILEPOS); } params->ret_values = params->list.count; call_exp->list.add(params OS_DBG_FILEPOS); } call_exp->ret_values = params->list.count; // var valid, k, v = func(state, state2) String assing_operator(allocator, OS_TEXT("=")); TokenData * assign_token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(tokenizer->getTextData(), assing_operator, Tokenizer::OPERATOR_ASSIGN, loop_scope->token->line, loop_scope->token->pos); exp = newBinaryExpression(scope, EXP_TYPE_ASSIGN, assign_token, params, call_exp); OS_ASSERT(exp && exp->type == EXP_TYPE_SET_LOCAL_VAR && !exp->ret_values); assign_token->release(); loop_scope->list.add(exp OS_DBG_FILEPOS); exp = NULL; } // if(!valid) break { Expression * var_exp = vars.lastElement(); // valid var Expression * name_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, var_exp->token); OS_ASSERT(scope->function); name_exp->active_locals = scope->function->num_locals; name_exp->ret_values = 1; Expression * not_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_LOGIC_NOT, loop_scope->token, name_exp OS_DBG_FILEPOS); not_exp->ret_values = 1; Expression * break_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_BREAK, loop_scope->token); Expression * if_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_IF, loop_scope->token, not_exp, break_exp OS_DBG_FILEPOS); loop_scope->list.add(if_exp OS_DBG_FILEPOS); } loop_scope->list.add(body_exp OS_DBG_FILEPOS); // assemble all exps scope->list.swap(vars); scope->list.add(newExpressionFromList(list, 0) OS_DBG_FILEPOS); return scope; } Expression * pre_exp = exp; if(recent_token->type != Tokenizer::CODE_SEPARATOR){ setError(Tokenizer::CODE_SEPARATOR, recent_token); allocator->deleteObj(scope); allocator->deleteObj(pre_exp); return NULL; } readToken(); Expression * bool_exp; if(recent_token->type == Tokenizer::CODE_SEPARATOR){ bool_exp = NULL; }else{ bool_exp = expectSingleExpression(scope, Params().setAllowAutoCall(true).setAllowBinaryOperator(true)); if(!bool_exp){ allocator->deleteObj(scope); allocator->deleteObj(pre_exp); return NULL; } } if(bool_exp && !bool_exp->ret_values){ setError(ERROR_EXPECT_VALUE, bool_exp->token); allocator->deleteObj(scope); allocator->deleteObj(pre_exp); allocator->deleteObj(bool_exp); return NULL; } if(recent_token->type != Tokenizer::CODE_SEPARATOR){ setError(Tokenizer::CODE_SEPARATOR, recent_token); allocator->deleteObj(scope); allocator->deleteObj(pre_exp); allocator->deleteObj(bool_exp); return NULL; } readToken(); Expression * post_exp = expectSingleExpression(scope, Params() .setAllowAssign(true) .setAllowAutoCall(true) .setAllowBinaryOperator(true) .setAllowNopResult(true)); if(!post_exp){ allocator->deleteObj(scope); allocator->deleteObj(pre_exp); allocator->deleteObj(bool_exp); return NULL; } if(recent_token->type != Tokenizer::END_BRACKET_BLOCK){ setError(Tokenizer::END_BRACKET_BLOCK, recent_token); allocator->deleteObj(scope); allocator->deleteObj(pre_exp); allocator->deleteObj(bool_exp); allocator->deleteObj(post_exp); return NULL; } readToken(); Scope * loop_scope = new (malloc(sizeof(Scope) OS_DBG_FILEPOS)) Scope(scope, EXP_TYPE_LOOP_SCOPE, recent_token); Expression * body_exp = expectSingleExpression(loop_scope, true, true); if(!body_exp){ allocator->deleteObj(scope); allocator->deleteObj(pre_exp); allocator->deleteObj(bool_exp); allocator->deleteObj(post_exp); allocator->deleteObj(loop_scope); return NULL; } if(bool_exp){ bool_exp = expectExpressionValues(bool_exp, 1); Expression * not_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_LOGIC_NOT, bool_exp->token, bool_exp OS_DBG_FILEPOS); not_exp->ret_values = 1; Expression * break_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_BREAK, bool_exp->token); Expression * if_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_IF, bool_exp->token, not_exp, break_exp OS_DBG_FILEPOS); loop_scope->list.add(if_exp OS_DBG_FILEPOS); } body_exp = expectExpressionValues(body_exp, 0); loop_scope->list.add(body_exp OS_DBG_FILEPOS); post_exp = expectExpressionValues(post_exp, 0); loop_scope->list.add(post_exp OS_DBG_FILEPOS); scope->list.add(pre_exp OS_DBG_FILEPOS); scope->list.add(loop_scope OS_DBG_FILEPOS); return scope; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectDebugLocalsExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_debuglocals); Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_DEBUG_LOCALS, recent_token); exp->ret_values = 1; readToken(); return exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectIfExpression(Scope * scope) { OS_ASSERT(recent_token && (recent_token->str == allocator->core->strings->syntax_if || recent_token->str == allocator->core->strings->syntax_elseif)); if(!expectToken(Tokenizer::BEGIN_BRACKET_BLOCK) || !expectToken()){ return NULL; } TokenData * token = recent_token; Expression * if_exp = expectSingleExpression(scope, Params().setAllowBinaryOperator(true).setAllowNopResult(true)); if(!if_exp){ return NULL; } if(if_exp->ret_values < 1){ setError(ERROR_EXPECT_VALUE, token); allocator->deleteObj(if_exp); return NULL; } if_exp = expectExpressionValues(if_exp, 1); if(!recent_token || recent_token->type != Tokenizer::END_BRACKET_BLOCK){ setError(Tokenizer::END_BRACKET_BLOCK, recent_token); allocator->deleteObj(if_exp); return NULL; } if(!expectToken()){ allocator->deleteObj(if_exp); return NULL; } if(!recent_token){ setError(ERROR_EXPECT_TOKEN, recent_token); allocator->deleteObj(if_exp); return NULL; } token = recent_token; Expression * then_exp = expectSingleExpression(scope, true, true); /* if(recent_token->type == Tokenizer::BEGIN_CODE_BLOCK){ then_exp = expectCodeExpression(scope); }else{ then_exp = expectSingleExpression(scope, true); } */ if(!then_exp){ allocator->deleteObj(if_exp); return NULL; } then_exp = expectExpressionValues(then_exp, 0); if(recent_token && recent_token->type == Tokenizer::NAME){ Expression * else_exp = NULL; if(recent_token->str == allocator->core->strings->syntax_elseif){ if(!expectToken()){ allocator->deleteObj(if_exp); allocator->deleteObj(then_exp); return NULL; } else_exp = expectIfExpression(scope); }else if(recent_token->str == allocator->core->strings->syntax_else){ if(!expectToken()){ allocator->deleteObj(if_exp); allocator->deleteObj(then_exp); return NULL; } token = recent_token; else_exp = expectSingleExpression(scope, true, true); /* if(recent_token->type == Tokenizer::BEGIN_CODE_BLOCK){ else_exp = expectCodeExpression(scope); }else{ else_exp = expectSingleExpression(scope); } */ }else{ return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_IF, if_exp->token, if_exp, then_exp OS_DBG_FILEPOS); } if(!else_exp){ allocator->deleteObj(if_exp); allocator->deleteObj(then_exp); return NULL; } else_exp = expectExpressionValues(else_exp, 0); return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_IF, if_exp->token, if_exp, then_exp, else_exp OS_DBG_FILEPOS); } return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_IF, if_exp->token, if_exp, then_exp OS_DBG_FILEPOS); } OS::Core::Compiler::Expression * OS::Core::Compiler::expectReturnExpression(Scope * scope) { OS_ASSERT(recent_token && recent_token->str == allocator->core->strings->syntax_return); Expression * ret_exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_RETURN, recent_token); if(!readToken()){ setError(ERROR_SYNTAX, recent_token); allocator->deleteObj(ret_exp); return NULL; } switch(recent_token->type){ case Tokenizer::END_ARRAY_BLOCK: case Tokenizer::END_BRACKET_BLOCK: case Tokenizer::END_CODE_BLOCK: case Tokenizer::CODE_SEPARATOR: return ret_exp; } Expression * exp = expectSingleExpression(scope, Params().setAllowBinaryOperator(true).setAllowParams(true)); if(!exp){ allocator->deleteObj(ret_exp); return NULL; } if(exp->type == EXP_TYPE_PARAMS){ ret_exp->list.swap(exp->list); ret_exp->ret_values = exp->ret_values; allocator->deleteObj(exp); }else{ ret_exp->list.add(exp OS_DBG_FILEPOS); ret_exp->ret_values = exp->ret_values; } return ret_exp; } OS::Core::Compiler::Expression * OS::Core::Compiler::newBinaryExpression(Scope * scope, ExpressionType exp_type, TokenData * token, Expression * left_exp, Expression * right_exp) { // OS_ASSERT(token->isTypeOf(Tokenizer::BINARY_OPERATOR)); if(left_exp->isConstValue() && right_exp->isConstValue()){ struct Lib { Compiler * compiler; TokenData * token; void * malloc(int size OS_DBG_FILEPOS_DECL) { return compiler->malloc(size OS_DBG_FILEPOS_PARAM); } Expression * newExpression(const String& str, Expression * left_exp, Expression * right_exp) { token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(token->text_data, str, Tokenizer::STRING, token->line, token->pos); Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_STRING, token); exp->ret_values = 1; token->release(); compiler->allocator->deleteObj(left_exp); compiler->allocator->deleteObj(right_exp); return exp; } Expression * newExpression(OS_FLOAT val, Expression * left_exp, Expression * right_exp) { token = new (malloc(sizeof(TokenData) OS_DBG_FILEPOS)) TokenData(token->text_data, String(compiler->allocator, val), Tokenizer::NUMBER, token->line, token->pos); token->setFloat(val); Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NUMBER, token); exp->ret_values = 1; token->release(); compiler->allocator->deleteObj(left_exp); compiler->allocator->deleteObj(right_exp); return exp; } Expression * newExpression(OS_INT val, Expression * left_exp, Expression * right_exp) { return newExpression((OS_FLOAT)val, left_exp, right_exp); } Expression * switchExpression(bool ret_left, Expression * left_exp, Expression * right_exp) { if(ret_left){ compiler->allocator->deleteObj(right_exp); return left_exp; } compiler->allocator->deleteObj(left_exp); return right_exp; } } lib = {this, token}; switch(exp_type){ case EXP_TYPE_CONCAT: // .. return lib.newExpression(String(allocator->core->newStringValue(left_exp->toString(), right_exp->toString())), left_exp, right_exp); // case EXP_TYPE_ANY_PARAMS: // ... /* case EXP_TYPE_LOGIC_AND: // && return lib.switchExpression(left_exp->toInt() == 0, left_exp, right_exp); case EXP_TYPE_LOGIC_OR: // || return lib.switchExpression(left_exp->toInt() != 0, left_exp, right_exp); */ /* case EXP_TYPE_LOGIC_PTR_EQ: // === case EXP_TYPE_LOGIC_PTR_NE: // !== case EXP_TYPE_LOGIC_EQ: // == case EXP_TYPE_LOGIC_NE: // != case EXP_TYPE_LOGIC_GE: // >= case EXP_TYPE_LOGIC_LE: // <= case EXP_TYPE_LOGIC_GREATER: // > case EXP_TYPE_LOGIC_LESS: // < */ // case EXP_TYPE_LOGIC_NOT: // ! // case EXP_TYPE_INC: // ++ // case EXP_TYPE_DEC: // -- // case EXP_TYPE_QUESTION: // ? // case EXP_TYPE_COLON: // : case EXP_TYPE_BIT_AND: // & return lib.newExpression(left_exp->toInt() & right_exp->toInt(), left_exp, right_exp); case EXP_TYPE_BIT_OR: // | return lib.newExpression(left_exp->toInt() | right_exp->toInt(), left_exp, right_exp); case EXP_TYPE_BIT_XOR: // ^ return lib.newExpression(left_exp->toInt() ^ right_exp->toInt(), left_exp, right_exp); // case EXP_TYPE_BIT_NOT: // ~ case EXP_TYPE_ADD: // + return lib.newExpression(left_exp->toNumber() + right_exp->toNumber(), left_exp, right_exp); case EXP_TYPE_SUB: // - return lib.newExpression(left_exp->toNumber() - right_exp->toNumber(), left_exp, right_exp); case EXP_TYPE_MUL: // * return lib.newExpression(left_exp->toNumber() * right_exp->toNumber(), left_exp, right_exp); case EXP_TYPE_DIV: // / return lib.newExpression(left_exp->toNumber() / right_exp->toNumber(), left_exp, right_exp); case EXP_TYPE_MOD: // % return lib.newExpression(OS_MATH_MOD_OPERATOR(left_exp->toNumber(), right_exp->toNumber()), left_exp, right_exp); case EXP_TYPE_LSHIFT: // << return lib.newExpression(left_exp->toInt() << right_exp->toInt(), left_exp, right_exp); case EXP_TYPE_RSHIFT: // >> return lib.newExpression(left_exp->toInt() >> right_exp->toInt(), left_exp, right_exp); case EXP_TYPE_POW: // ** return lib.newExpression(OS_MATH_POW_OPERATOR(left_exp->toNumber(), right_exp->toNumber()), left_exp, right_exp); } } switch(exp_type){ case EXP_TYPE_QUESTION: return finishQuestionOperator(scope, token, left_exp, right_exp); case EXP_TYPE_ASSIGN: { if(left_exp->type != EXP_TYPE_PARAMS){ right_exp = expectExpressionValues(right_exp, 1); return newAssingExpression(scope, left_exp, right_exp); } Expression * values_exp = expectExpressionValues(right_exp, left_exp->list.count); for(int i = left_exp->list.count-1; i >= 0; i--){ OS_ASSERT(values_exp->ret_values > 0); Expression * var_exp = left_exp->list[i]; left_exp->list.removeIndex(i); // left_exp is going to be deleted values_exp = newAssingExpression(scope, var_exp, values_exp); if(!values_exp){ break; } } allocator->deleteObj(left_exp); return values_exp; } } if(left_exp->type == EXP_TYPE_PARAMS){ OS_ASSERT(right_exp->type != EXP_TYPE_PARAMS); right_exp = expectExpressionValues(right_exp, 1); left_exp->list.add(right_exp OS_DBG_FILEPOS); left_exp->ret_values++; return left_exp; } if(right_exp->type == EXP_TYPE_PARAMS){ Expression * params = right_exp; OS_ASSERT(params->list.count > 0); if(params->list.count == 1){ right_exp = params->list[0]; allocator->vectorClear(params->list); allocator->deleteObj(params); }else{ left_exp = expectExpressionValues(left_exp, 1); allocator->vectorInsertAtIndex(params->list, 0, left_exp OS_DBG_FILEPOS); params->ret_values++; return params; } } left_exp = expectExpressionValues(left_exp, 1); right_exp = expectExpressionValues(right_exp, 1); Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp_type, token, left_exp, right_exp OS_DBG_FILEPOS); exp->ret_values = exp_type == EXP_TYPE_PARAMS ? 2 : 1; return exp; } bool OS::Core::Compiler::findLocalVar(LocalVarDesc& desc, Scope * scope, const String& name, int active_locals, bool all_scopes) { OS_ASSERT(scope); for(int up_count = 0, up_scope_count = 0;;){ for(int i = scope->locals.count-1; i >= 0; i--){ const Scope::LocalVar& local_var = scope->locals[i]; if((up_count || local_var.index < active_locals) && local_var.name == name){ desc.index = local_var.index; desc.up_count = up_count; desc.up_scope_count = up_scope_count; desc.type = i < scope->num_params ? LOCAL_PARAM : (name.toChar()[0] != OS_TEXT('#') ? LOCAL_GENERIC : LOCAL_TEMP); return true; } } if(scope->parent){ if(!all_scopes){ return false; } if(scope->type == EXP_TYPE_FUNCTION){ up_count++; } up_scope_count++; scope = scope->parent; continue; } break; } return false; } OS::Core::Compiler::Expression * OS::Core::Compiler::newAssingExpression(Scope * scope, Expression * var_exp, Expression * value_exp) { switch(var_exp->type){ case EXP_TYPE_CALL_DIM: { Expression * name_exp = var_exp->list[0]; Expression * params = var_exp->list[1]; OS_ASSERT(params->type == EXP_TYPE_PARAMS); allocator->vectorInsertAtIndex(var_exp->list, 0, value_exp OS_DBG_FILEPOS); var_exp->type = EXP_TYPE_SET_DIM; var_exp->ret_values = value_exp->ret_values-1; return var_exp; } case EXP_TYPE_INDIRECT: { OS_ASSERT(var_exp->list.count == 2); Expression * var_exp_left = var_exp->list[0]; switch(var_exp_left->type){ case EXP_TYPE_NAME: { OS_ASSERT(var_exp_left->ret_values == 1); if(findLocalVar(var_exp_left->local_var, scope, var_exp_left->token->str, var_exp_left->active_locals, true)){ var_exp_left->type = EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE; if(scope->function->max_up_count < var_exp_left->local_var.up_count){ scope->function->max_up_count = var_exp_left->local_var.up_count; } }else{ var_exp_left->type = EXP_TYPE_GET_ENV_VAR_AUTO_CREATE; } break; } } ExpressionType exp_type = EXP_TYPE_SET_PROPERTY; Expression * var_exp_right = var_exp->list[1]; switch(var_exp_right->type){ case EXP_TYPE_NAME: OS_ASSERT(var_exp_right->ret_values == 1); var_exp_right->type = EXP_TYPE_CONST_STRING; break; case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: OS_ASSERT(false); return NULL; case EXP_TYPE_CALL_DIM: OS_ASSERT(false); return NULL; } Expression * exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(exp_type, var_exp->token, value_exp, var_exp_left, var_exp_right OS_DBG_FILEPOS); exp->ret_values = value_exp->ret_values-1; allocator->vectorClear(var_exp->list); allocator->deleteObj(var_exp); return exp; } break; case EXP_TYPE_NAME: if(findLocalVar(var_exp->local_var, scope, var_exp->token->str, var_exp->active_locals, true)){ var_exp->type = EXP_TYPE_SET_LOCAL_VAR; if(scope->function->max_up_count < var_exp->local_var.up_count){ scope->function->max_up_count = var_exp->local_var.up_count; } }else{ var_exp->type = EXP_TYPE_SET_ENV_VAR; } var_exp->list.add(value_exp OS_DBG_FILEPOS); var_exp->ret_values = value_exp->ret_values-1; return var_exp; default: // OS_ASSERT(false); if(!var_exp->isWriteable()){ setError(ERROR_EXPECT_WRITEABLE, var_exp->token); allocator->deleteObj(var_exp); allocator->deleteObj(value_exp); return NULL; } } return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_ASSIGN, var_exp->token, var_exp, value_exp OS_DBG_FILEPOS); } OS::Core::Compiler::Expression * OS::Core::Compiler::finishBinaryOperator(Scope * scope, OpcodeLevel prev_level, Expression * exp, const Params& _p, bool& is_finished) { TokenData * binary_operator = recent_token; OS_ASSERT(binary_operator->isTypeOf(Tokenizer::BINARY_OPERATOR)); Params p = Params(_p) .setAllowAssign(false) .setAllowBinaryOperator(false) .setAllowInOperator(_p.allow_in_operator) // .setAllowParams(false) .setAllowAutoCall(false) // binary_operator->type == Tokenizer::OPERATOR_ASSIGN) .setAllowRootBlocks(false); readToken(); Expression * exp2 = expectSingleExpression(scope, Params(p).setAllowParams(false)); // false, allow_param, false, false, false); if(!exp2){ /* if(!isError()){ return exp; } */ is_finished = true; allocator->deleteObj(exp); return NULL; } // exp2 = expectExpressionValues(exp2, 1); if(recent_token && recent_token->type == Tokenizer::NAME){ if(recent_token->str == allocator->core->strings->syntax_in){ if(p.allow_in_operator){ recent_token->type = Tokenizer::OPERATOR_IN; } }else if(recent_token->str == allocator->core->strings->syntax_isprototypeof){ recent_token->type = Tokenizer::OPERATOR_ISPROTOTYPEOF; }else if(recent_token->str == allocator->core->strings->syntax_is){ recent_token->type = Tokenizer::OPERATOR_IS; } } if(!recent_token || !recent_token->isTypeOf(Tokenizer::BINARY_OPERATOR) || (!p.allow_params && recent_token->type == Tokenizer::PARAM_SEPARATOR)){ // return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(getExpressionType(binary_operator->type), binary_operator, exp, exp2); is_finished = true; return newBinaryExpression(scope, getExpressionType(binary_operator->type), binary_operator, exp, exp2); } ExpressionType left_exp_type = getExpressionType(binary_operator->type); ExpressionType right_exp_type = getExpressionType(recent_token->type); OpcodeLevel left_level = getOpcodeLevel(left_exp_type); OpcodeLevel right_level = getOpcodeLevel(right_exp_type); if(left_level == right_level){ // exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(left_exp_type, binary_operator, exp, exp2); exp = newBinaryExpression(scope, left_exp_type, binary_operator, exp, exp2); return finishBinaryOperator(scope, prev_level, exp, p, is_finished); } if(left_level > right_level){ // exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(left_exp_type, binary_operator, exp, exp2); exp = newBinaryExpression(scope, left_exp_type, binary_operator, exp, exp2); if(prev_level >= right_level){ is_finished = false; return exp; } return finishBinaryOperator(scope, prev_level, exp, p, is_finished); } exp2 = finishBinaryOperator(scope, left_level, exp2, p, is_finished); if(!exp2){ allocator->deleteObj(exp); return NULL; } exp = newBinaryExpression(scope, left_exp_type, binary_operator, exp, exp2); if(is_finished){ // !recent_token || !recent_token->isTypeOf(Tokenizer::BINARY_OPERATOR)){ return exp; } return finishBinaryOperator(scope, prev_level, exp, p, is_finished); } OS::Core::Compiler::Expression * OS::Core::Compiler::finishValueExpressionNoAutoCall(Scope * scope, Expression * exp, const Params& p) { return finishValueExpression(scope, exp, Params(p).setAllowAutoCall(false)); } OS::Core::Compiler::Expression * OS::Core::Compiler::finishValueExpressionNoNextCall(Scope * scope, Expression * exp, const Params& p) { if(recent_token && recent_token->type == Tokenizer::BEGIN_BRACKET_BLOCK){ return exp; } return finishValueExpression(scope, exp, Params(p).setAllowAutoCall(false)); } OS::Core::Compiler::Expression * OS::Core::Compiler::finishValueExpression(Scope * scope, Expression * exp, const Params& _p) { bool is_finished; Params p = Params(_p) .setAllowRootBlocks(false); bool next_allow_auto_call = false; for(;; p.allow_auto_call = next_allow_auto_call, next_allow_auto_call = false){ if(!recent_token){ return exp; } Expression * exp2; TokenData * token = recent_token; TokenType token_type = token->type; switch(token_type){ case Tokenizer::OPERATOR_INDIRECT: // . // setError(ERROR_SYNTAX, token); // return NULL; token = expectToken(Tokenizer::NAME); if(!token){ allocator->deleteObj(exp); return NULL; } exp2 = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, token); exp2->ret_values = 1; OS_ASSERT(scope->function); exp2->active_locals = scope->function->num_locals; exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_INDIRECT, exp2->token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; readToken(); // p.setAllowCall(true); next_allow_auto_call = p.allow_auto_call; continue; // post ++, post -- case Tokenizer::OPERATOR_INC: case Tokenizer::OPERATOR_DEC: if(exp->type != EXP_TYPE_NAME){ return exp; } OS_ASSERT(exp->ret_values == 1); if(!findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, true)){ setError(ERROR_LOCAL_VAL_NOT_DECLARED, exp->token); allocator->deleteObj(exp); return NULL; } if(scope->function->max_up_count < exp->local_var.up_count){ scope->function->max_up_count = exp->local_var.up_count; } exp->type = EXP_TYPE_GET_LOCAL_VAR; exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(token_type == Tokenizer::OPERATOR_INC ? EXP_TYPE_POST_INC : EXP_TYPE_POST_DEC, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); case Tokenizer::OPERATOR_CONCAT: // .. // case Tokenizer::REST_ARGUMENTS: // ... case Tokenizer::OPERATOR_LOGIC_AND: // && case Tokenizer::OPERATOR_LOGIC_OR: // || case Tokenizer::OPERATOR_LOGIC_PTR_EQ: // === case Tokenizer::OPERATOR_LOGIC_PTR_NE: // !== case Tokenizer::OPERATOR_LOGIC_EQ: // == case Tokenizer::OPERATOR_LOGIC_NE: // != case Tokenizer::OPERATOR_LOGIC_GE: // >= case Tokenizer::OPERATOR_LOGIC_LE: // <= case Tokenizer::OPERATOR_LOGIC_GREATER: // > case Tokenizer::OPERATOR_LOGIC_LESS: // < case Tokenizer::OPERATOR_LOGIC_NOT: // ! // case Tokenizer::OPERATOR_INC: // ++ // case Tokenizer::OPERATOR_DEC: // -- case Tokenizer::OPERATOR_QUESTION: // ? // case Tokenizer::OPERATOR_COLON: // : case Tokenizer::OPERATOR_BIT_AND: // & case Tokenizer::OPERATOR_BIT_OR: // | case Tokenizer::OPERATOR_BIT_XOR: // ^ case Tokenizer::OPERATOR_BIT_NOT: // ~ case Tokenizer::OPERATOR_ADD: // + case Tokenizer::OPERATOR_SUB: // - case Tokenizer::OPERATOR_MUL: // * case Tokenizer::OPERATOR_DIV: // / case Tokenizer::OPERATOR_MOD: // % case Tokenizer::OPERATOR_LSHIFT: // << case Tokenizer::OPERATOR_RSHIFT: // >> case Tokenizer::OPERATOR_POW: // ** if(!p.allow_binary_operator){ return exp; } exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, p, is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); continue; case Tokenizer::PARAM_SEPARATOR: if(!p.allow_params){ return exp; } exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, p, is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); continue; case Tokenizer::OPERATOR_BIT_AND_ASSIGN: // &= case Tokenizer::OPERATOR_BIT_OR_ASSIGN: // |= case Tokenizer::OPERATOR_BIT_XOR_ASSIGN: // ^= case Tokenizer::OPERATOR_BIT_NOT_ASSIGN: // ~= case Tokenizer::OPERATOR_ADD_ASSIGN: // += case Tokenizer::OPERATOR_SUB_ASSIGN: // -= case Tokenizer::OPERATOR_MUL_ASSIGN: // *= case Tokenizer::OPERATOR_DIV_ASSIGN: // /= case Tokenizer::OPERATOR_MOD_ASSIGN: // %= case Tokenizer::OPERATOR_LSHIFT_ASSIGN: // <<= case Tokenizer::OPERATOR_RSHIFT_ASSIGN: // >>= case Tokenizer::OPERATOR_POW_ASSIGN: // **= setError(ERROR_SYNTAX, token); return NULL; case Tokenizer::OPERATOR_ASSIGN: // = if(!p.allow_assing){ // allow_binary_operator){ return exp; } exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, Params(p).setAllowAssign(false), is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); return exp; case Tokenizer::END_ARRAY_BLOCK: case Tokenizer::END_BRACKET_BLOCK: case Tokenizer::END_CODE_BLOCK: case Tokenizer::CODE_SEPARATOR: return exp; case Tokenizer::BEGIN_CODE_BLOCK: // { /* if(!p.allow_auto_call){ return exp; } */ exp2 = expectObjectExpression(scope, p, false); if(!exp2){ allocator->deleteObj(exp); return NULL; } OS_ASSERT(exp2->ret_values == 1); exp2 = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, exp2->token, exp2 OS_DBG_FILEPOS); exp2->ret_values = 1; exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL_AUTO_PARAM, token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; // allow_auto_call = false; continue; case Tokenizer::NAME: if(token->str == allocator->core->strings->syntax_in){ if(!p.allow_in_operator || !p.allow_binary_operator){ return exp; } token->type = Tokenizer::OPERATOR_IN; exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, p, is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); continue; } if(token->str == allocator->core->strings->syntax_isprototypeof){ if(!p.allow_binary_operator){ return exp; } token->type = Tokenizer::OPERATOR_ISPROTOTYPEOF; exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, p, is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); continue; } if(token->str == allocator->core->strings->syntax_is){ if(!p.allow_binary_operator){ return exp; } token->type = Tokenizer::OPERATOR_IS; exp = finishBinaryOperator(scope, OP_LEVEL_NOTHING, exp, p, is_finished); if(!exp){ return NULL; } OS_ASSERT(is_finished); continue; } // no break default: if(!p.allow_auto_call){ return exp; } if(token->type == Tokenizer::NAME){ if(token->str == allocator->core->strings->syntax_var // || token->str == allocator->core->strings->syntax_function || token->str == allocator->core->strings->syntax_return || token->str == allocator->core->strings->syntax_if || token->str == allocator->core->strings->syntax_else || token->str == allocator->core->strings->syntax_elseif || token->str == allocator->core->strings->syntax_for || token->str == allocator->core->strings->syntax_break || token->str == allocator->core->strings->syntax_continue || token->str == allocator->core->strings->syntax_in || token->str == allocator->core->strings->syntax_class || token->str == allocator->core->strings->syntax_enum || token->str == allocator->core->strings->syntax_switch || token->str == allocator->core->strings->syntax_case || token->str == allocator->core->strings->syntax_default || token->str == allocator->core->strings->syntax_debugger // || token->str == allocator->core->strings->syntax_debuglocals ) { return exp; } } exp2 = expectSingleExpression(scope, Params(p) .setAllowAssign(false) .setAllowAutoCall(false) .setAllowParams(false) .setAllowRootBlocks(false)); // allow_binary_operator, false, false, false, false); if(!exp2){ allocator->deleteObj(exp); return NULL; } OS_ASSERT(exp2->ret_values == 1); exp2 = expectExpressionValues(exp2, 1); exp2 = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_PARAMS, exp2->token, exp2 OS_DBG_FILEPOS); exp2->ret_values = 1; exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL_AUTO_PARAM, token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; // allow_auto_call = false; continue; case Tokenizer::BEGIN_BRACKET_BLOCK: // ( if(!p.allow_call){ return exp; } exp2 = expectParamsExpression(scope); if(!exp2){ allocator->deleteObj(exp); return NULL; } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL, token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; continue; case Tokenizer::BEGIN_ARRAY_BLOCK: // [ exp2 = expectParamsExpression(scope); if(!exp2){ allocator->deleteObj(exp); return NULL; } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CALL_DIM, token, exp, exp2 OS_DBG_FILEPOS); exp->ret_values = 1; if(0 && !p.allow_binary_operator){ return exp; } continue; } } return NULL; // shut up compiler } OS::Core::Compiler::Params::Params() { OS_MEMSET(this, 0, sizeof(*this)); allow_call = true; } OS::Core::Compiler::Params::Params(const Params& p) { OS_MEMCPY(this, &p, sizeof(p)); } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowRootBlocks(bool val) { allow_root_blocks = val; allow_var_decl = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowVarDecl(bool val) { allow_var_decl = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowInlineNestedBlock(bool val) { allow_inline_nested_block = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowBinaryOperator(bool val) { allow_binary_operator = val; allow_in_operator = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowInOperator(bool val) { allow_in_operator = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowAssign(bool val) { allow_assing = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowParams(bool val) { allow_params = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowAutoCall(bool val) { allow_auto_call = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowCall(bool val) { allow_call = val; return *this; } OS::Core::Compiler::Params& OS::Core::Compiler::Params::setAllowNopResult(bool val) { allow_nop_result = val; return *this; } bool OS::Core::Compiler::isVarNameValid(const String& name) { const String * list[] = { &allocator->core->strings->syntax_super, &allocator->core->strings->syntax_is, &allocator->core->strings->syntax_isprototypeof, &allocator->core->strings->syntax_typeof, &allocator->core->strings->syntax_valueof, &allocator->core->strings->syntax_booleanof, &allocator->core->strings->syntax_numberof, &allocator->core->strings->syntax_stringof, &allocator->core->strings->syntax_arrayof, &allocator->core->strings->syntax_objectof, &allocator->core->strings->syntax_userdataof, &allocator->core->strings->syntax_functionof, &allocator->core->strings->syntax_extends, &allocator->core->strings->syntax_clone, &allocator->core->strings->syntax_delete, &allocator->core->strings->syntax_prototype, &allocator->core->strings->syntax_var, &allocator->core->strings->syntax_this, &allocator->core->strings->syntax_arguments, &allocator->core->strings->syntax_function, &allocator->core->strings->syntax_null, &allocator->core->strings->syntax_true, &allocator->core->strings->syntax_false, &allocator->core->strings->syntax_return, &allocator->core->strings->syntax_class, &allocator->core->strings->syntax_enum, &allocator->core->strings->syntax_switch, &allocator->core->strings->syntax_case, &allocator->core->strings->syntax_default, &allocator->core->strings->syntax_if, &allocator->core->strings->syntax_else, &allocator->core->strings->syntax_elseif, &allocator->core->strings->syntax_for, &allocator->core->strings->syntax_in, &allocator->core->strings->syntax_break, &allocator->core->strings->syntax_continue, &allocator->core->strings->syntax_debugger, &allocator->core->strings->syntax_debuglocals }; for(int i = 0; i < (int)(sizeof(list)/sizeof(list[0])); i++){ if(name == *(list[i])){ return false; } } return true; } OS::Core::Compiler::Expression * OS::Core::Compiler::expectSingleExpression(Scope * scope, bool allow_nop_result, bool allow_inline_nested_block) { return expectSingleExpression(scope, Params() .setAllowAssign(true) .setAllowAutoCall(true) .setAllowBinaryOperator(true) .setAllowParams(true) .setAllowRootBlocks(true) .setAllowNopResult(allow_nop_result) .setAllowInlineNestedBlock(allow_inline_nested_block)); } OS::Core::Compiler::Expression * OS::Core::Compiler::expectSingleExpression(Scope * scope, const Params& p) { #ifdef OS_DEBUG allocator->checkNativeStackUsage(OS_TEXT("OS::Core::Compiler::expectSingleExpression")); #endif TokenData * token = recent_token; // readToken(); if(!token){ setError(ERROR_EXPECT_EXPRESSION, token); return NULL; } Expression * exp; TokenType token_type = token->type; switch(token_type){ // begin unary operators case Tokenizer::OPERATOR_ADD: case Tokenizer::OPERATOR_SUB: case Tokenizer::OPERATOR_LENGTH: case Tokenizer::OPERATOR_BIT_NOT: case Tokenizer::OPERATOR_LOGIC_NOT: if(!expectToken()){ return NULL; } exp = expectSingleExpression(scope, Params()); if(!exp){ return NULL; } OS_ASSERT(exp->ret_values == 1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(getUnaryExpressionType(token_type), exp->token, exp OS_DBG_FILEPOS); exp->ret_values = 1; return finishValueExpressionNoAutoCall(scope, exp, p); // allow_binary_operator, allow_param, allow_assign, false); // pre ++, pre -- case Tokenizer::OPERATOR_INC: case Tokenizer::OPERATOR_DEC: if(!expectToken(Tokenizer::NAME)){ return NULL; } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_LOCAL_VAR, recent_token); exp->ret_values = 1; exp->active_locals = scope->function->num_locals; if(!findLocalVar(exp->local_var, scope, exp->token->str, exp->active_locals, true)){ setError(ERROR_LOCAL_VAL_NOT_DECLARED, exp->token); allocator->deleteObj(exp); return NULL; } if(scope->function->max_up_count < exp->local_var.up_count){ scope->function->max_up_count = exp->local_var.up_count; } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(token_type == Tokenizer::OPERATOR_INC ? EXP_TYPE_PRE_INC : EXP_TYPE_PRE_DEC, exp->token, exp OS_DBG_FILEPOS); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); // end unary operators case Tokenizer::BEGIN_CODE_BLOCK: if(p.allow_root_blocks){ if(!p.allow_inline_nested_block){ TokenData * check_token = getPrevToken(); if(!check_token || (check_token->type != Tokenizer::CODE_SEPARATOR && check_token->type != Tokenizer::BEGIN_CODE_BLOCK)){ // setError(Tokenizer::CODE_SEPARATOR, recent_token); setError(ERROR_EXPECT_CODE_SEP_BEFORE_NESTED_BLOCK, recent_token); return NULL; } } return expectCodeExpression(scope); } return expectObjectExpression(scope, p); case Tokenizer::BEGIN_ARRAY_BLOCK: return expectArrayExpression(scope, p); case Tokenizer::BEGIN_BRACKET_BLOCK: return expectBracketExpression(scope, p); case Tokenizer::STRING: exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_STRING, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoNextCall(scope, exp, p); case Tokenizer::NUMBER: exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NUMBER, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoNextCall(scope, exp, p); case Tokenizer::REST_ARGUMENTS: exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_REST_ARGUMENTS, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoNextCall(scope, exp, p); case Tokenizer::CODE_SEPARATOR: case Tokenizer::END_ARRAY_BLOCK: case Tokenizer::END_BRACKET_BLOCK: case Tokenizer::END_CODE_BLOCK: if(!p.allow_nop_result){ return NULL; } return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NOP, token); case Tokenizer::NAME: if(token->str == allocator->core->strings->syntax_var){ if(!p.allow_var_decl){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } return expectVarExpression(scope); } if(token->str == allocator->core->strings->syntax_function){ exp = expectFunctionExpression(scope); if(!exp){ return NULL; } if(!exp->ret_values){ return exp; } return finishValueExpression(scope, exp, p); } if(token->str == allocator->core->strings->syntax_return){ return expectReturnExpression(scope); } if(token->str == allocator->core->strings->syntax_if){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } return expectIfExpression(scope); } if(token->str == allocator->core->strings->syntax_else){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_elseif){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_for){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } return expectForExpression(scope); } if(token->str == allocator->core->strings->syntax_in){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_this){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_THIS, token); exp->ret_values = 1; readToken(); return finishValueExpression(scope, exp, p); } if(token->str == allocator->core->strings->syntax_arguments){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_GET_ARGUMENTS, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_null){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_NULL, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_true){ token->setFloat(1); exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_TRUE, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_false){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONST_FALSE, token); exp->ret_values = 1; readToken(); return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_extends){ exp = expectExtendsExpression(scope); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_clone){ exp = expectCloneExpression(scope); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_delete){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } return expectDeleteExpression(scope); } if(token->str == allocator->core->strings->syntax_typeof){ exp = expectValueOfExpression(scope, EXP_TYPE_TYPE_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_valueof){ exp = expectValueOfExpression(scope, EXP_TYPE_VALUE_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_booleanof){ exp = expectValueOfExpression(scope, EXP_TYPE_LOGIC_BOOL); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_numberof){ exp = expectValueOfExpression(scope, EXP_TYPE_NUMBER_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_stringof){ exp = expectValueOfExpression(scope, EXP_TYPE_STRING_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_arrayof){ exp = expectValueOfExpression(scope, EXP_TYPE_ARRAY_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_objectof){ exp = expectValueOfExpression(scope, EXP_TYPE_OBJECT_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_userdataof){ exp = expectValueOfExpression(scope, EXP_TYPE_USERDATA_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_functionof){ exp = expectValueOfExpression(scope, EXP_TYPE_FUNCTION_OF); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_break){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } readToken(); return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_BREAK, token); } if(token->str == allocator->core->strings->syntax_continue){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } readToken(); return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_CONTINUE, token); } if(token->str == allocator->core->strings->syntax_debugger){ if(!p.allow_root_blocks){ setError(ERROR_NESTED_ROOT_BLOCK, token); return NULL; } readToken(); return new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_DEBUGGER, token); } if(token->str == allocator->core->strings->syntax_debuglocals){ exp = expectDebugLocalsExpression(scope); if(!exp){ return NULL; } return finishValueExpressionNoAutoCall(scope, exp, p); } if(token->str == allocator->core->strings->syntax_is){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_isprototypeof){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_class){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_enum){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_switch){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_case || token->str == allocator->core->strings->syntax_default){ setError(ERROR_SYNTAX, token); return NULL; } if(token->str == allocator->core->strings->syntax_super){ exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_SUPER, token); exp->ret_values = 1; readToken(); return finishValueExpression(scope, exp, p); } exp = new (malloc(sizeof(Expression) OS_DBG_FILEPOS)) Expression(EXP_TYPE_NAME, token); exp->ret_values = 1; OS_ASSERT(scope->function); exp->active_locals = scope->function->num_locals; readToken(); return finishValueExpression(scope, exp, p); } setError(ERROR_EXPECT_EXPRESSION, token); return NULL; } void OS::Core::Compiler::debugPrintSourceLine(StringBuffer& out, TokenData * token) { if(!token){ return; } bool filePrinted = false; if(recent_printed_text_data != token->text_data){ if(recent_printed_text_data){ recent_printed_text_data->release(); } filePrinted = true; recent_printed_line = -1; recent_printed_text_data = token->text_data->retain(); out += String::format(allocator, OS_TEXT("\n[FILE] %s"), token->text_data->filename.toChar()); } if(recent_printed_line != token->line && token->line >= 0){ recent_printed_line = token->line; String line = allocator->core->newStringValue(token->text_data->lines[token->line], true, true); out += String::format(allocator, OS_TEXT("\n[%d] %s\n\n"), token->line+1, line.toChar()); } else if(filePrinted){ out += String::format(allocator, OS_TEXT("\n")); } return; } const OS_CHAR * OS::Core::Compiler::getExpName(ExpressionType type) { switch(type){ case EXP_TYPE_NOP: return OS_TEXT("nop"); case EXP_TYPE_CODE_LIST: return OS_TEXT("code list"); case EXP_TYPE_CONST_NUMBER: return OS_TEXT("const number"); case EXP_TYPE_CONST_STRING: return OS_TEXT("const string"); case EXP_TYPE_CONST_NULL: return OS_TEXT("const null"); case EXP_TYPE_CONST_TRUE: return OS_TEXT("const true"); case EXP_TYPE_CONST_FALSE: return OS_TEXT("const false"); case EXP_TYPE_NAME: return OS_TEXT("name"); case EXP_TYPE_PARAMS: return OS_TEXT("params"); case EXP_TYPE_INDIRECT: return OS_TEXT("indirect"); case EXP_TYPE_SET_PROPERTY: return OS_TEXT("set property"); case EXP_TYPE_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: return OS_TEXT("set property by locals auto create"); case EXP_TYPE_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: return OS_TEXT("get & set property by locals auto create"); case EXP_TYPE_GET_PROPERTY: return OS_TEXT("get property"); case EXP_TYPE_GET_PROPERTY_BY_LOCALS: return OS_TEXT("get property by locals"); case EXP_TYPE_GET_PROPERTY_BY_LOCAL_AND_NUMBER: return OS_TEXT("get property by local & number"); case EXP_TYPE_GET_PROPERTY_AUTO_CREATE: return OS_TEXT("get property auto create"); case EXP_TYPE_SET_DIM: return OS_TEXT("set dim"); case EXP_TYPE_POP_VALUE: return OS_TEXT("pop"); case EXP_TYPE_CALL: case EXP_TYPE_CALL_AUTO_PARAM: return OS_TEXT("call"); case EXP_TYPE_CALL_DIM: return OS_TEXT("dim"); // case EXP_TYPE_GET_DIM: // return OS_TEXT("get dim"); case EXP_TYPE_CALL_METHOD: return OS_TEXT("call method"); case EXP_TYPE_TAIL_CALL_METHOD: return OS_TEXT("tail call method"); case EXP_TYPE_TAIL_CALL: return OS_TEXT("tail call"); case EXP_TYPE_VALUE: return OS_TEXT("single value"); case EXP_TYPE_EXTENDS: return OS_TEXT("extends"); case EXP_TYPE_CLONE: return OS_TEXT("clone"); case EXP_TYPE_DELETE: return OS_TEXT("delete"); case EXP_TYPE_RETURN: return OS_TEXT("return"); case EXP_TYPE_FUNCTION: return OS_TEXT("function"); case EXP_TYPE_SCOPE: return OS_TEXT("scope"); case EXP_TYPE_LOOP_SCOPE: return OS_TEXT("loop"); case EXP_TYPE_GET_THIS: return OS_TEXT("push this"); case EXP_TYPE_GET_ARGUMENTS: return OS_TEXT("push arguments"); case EXP_TYPE_GET_REST_ARGUMENTS: return OS_TEXT("push rest arguments"); case EXP_TYPE_GET_LOCAL_VAR: return OS_TEXT("get local var"); case EXP_TYPE_GET_LOCAL_VAR_AUTO_CREATE: return OS_TEXT("get local var auto create"); case EXP_TYPE_GET_ENV_VAR: return OS_TEXT("get env var"); case EXP_TYPE_GET_ENV_VAR_AUTO_CREATE: return OS_TEXT("get env var auto create"); case EXP_TYPE_SET_LOCAL_VAR: return OS_TEXT("set local var"); case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS: return OS_TEXT("set local var by bin operator locals"); case EXP_TYPE_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER: return OS_TEXT("set local var by bin operator local & number"); case EXP_TYPE_SET_ENV_VAR: return OS_TEXT("set env var"); case EXP_TYPE_BIN_OPERATOR_BY_LOCALS: return OS_TEXT("binary operator by locals"); case EXP_TYPE_BIN_OPERATOR_BY_LOCAL_AND_NUMBER: return OS_TEXT("binary operator by local & number"); case EXP_TYPE_ASSIGN: return OS_TEXT("operator ="); case EXP_TYPE_LOGIC_AND: // && return OS_TEXT("logic &&"); case EXP_TYPE_LOGIC_OR: // || return OS_TEXT("logic ||"); case EXP_TYPE_LOGIC_PTR_EQ: // === return OS_TEXT("logic ==="); case EXP_TYPE_LOGIC_PTR_NE: // !== return OS_TEXT("logic !=="); case EXP_TYPE_LOGIC_EQ: // == return OS_TEXT("logic =="); case EXP_TYPE_LOGIC_NE: // != return OS_TEXT("logic !="); case EXP_TYPE_LOGIC_GE: // >= return OS_TEXT("logic >="); case EXP_TYPE_LOGIC_LE: // <= return OS_TEXT("logic <="); case EXP_TYPE_LOGIC_GREATER: // > return OS_TEXT("logic >"); case EXP_TYPE_LOGIC_LESS: // < return OS_TEXT("logic <"); case EXP_TYPE_LOGIC_BOOL: // !! return OS_TEXT("logic bool"); case EXP_TYPE_LOGIC_NOT: // ! return OS_TEXT("logic not"); case EXP_TYPE_PLUS: return OS_TEXT("plus"); case EXP_TYPE_NEG: return OS_TEXT("neg"); case EXP_TYPE_LENGTH: return OS_TEXT("length"); case EXP_TYPE_IN: return OS_TEXT("in"); case EXP_TYPE_ISPROTOTYPEOF: return OS_TEXT("isprototypeof"); case EXP_TYPE_IS: return OS_TEXT("is"); case EXP_TYPE_SUPER: return OS_TEXT("super"); case EXP_TYPE_TYPE_OF: return OS_TEXT("typeof"); case EXP_TYPE_VALUE_OF: return OS_TEXT("valueof"); case EXP_TYPE_NUMBER_OF: return OS_TEXT("numberof"); case EXP_TYPE_STRING_OF: return OS_TEXT("stringof"); case EXP_TYPE_ARRAY_OF: return OS_TEXT("arrayof"); case EXP_TYPE_OBJECT_OF: return OS_TEXT("objectof"); case EXP_TYPE_USERDATA_OF: return OS_TEXT("userdataof"); case EXP_TYPE_FUNCTION_OF: return OS_TEXT("functionof"); /* case EXP_TYPE_INC: // ++ return OS_TEXT("operator ++"); case EXP_TYPE_DEC: // -- return OS_TEXT("operator --"); */ case EXP_TYPE_PRE_INC: // ++ return OS_TEXT("pre ++"); case EXP_TYPE_PRE_DEC: // -- return OS_TEXT("pre --"); case EXP_TYPE_POST_INC: // ++ return OS_TEXT("post ++"); case EXP_TYPE_POST_DEC: // -- return OS_TEXT("post --"); case EXP_TYPE_BIT_AND: // & return OS_TEXT("bit &"); case EXP_TYPE_BIT_OR: // | return OS_TEXT("bit |"); case EXP_TYPE_BIT_XOR: // ^ return OS_TEXT("bit ^"); case EXP_TYPE_BIT_NOT: // ~ return OS_TEXT("bit ~"); case EXP_TYPE_BIT_AND_ASSIGN: // &= return OS_TEXT("bit &="); case EXP_TYPE_BIT_OR_ASSIGN: // |= return OS_TEXT("bit |="); case EXP_TYPE_BIT_XOR_ASSIGN: // ^= return OS_TEXT("bit ^="); case EXP_TYPE_BIT_NOT_ASSIGN: // ~= return OS_TEXT("bit ~="); case EXP_TYPE_CONCAT: // .. return OS_TEXT("operator .."); case EXP_TYPE_ADD: // + return OS_TEXT("operator +"); case EXP_TYPE_SUB: // - return OS_TEXT("operator -"); case EXP_TYPE_MUL: // * return OS_TEXT("operator *"); case EXP_TYPE_DIV: // / return OS_TEXT("operator /"); case EXP_TYPE_MOD: // % return OS_TEXT("operator %"); case EXP_TYPE_LSHIFT: // << return OS_TEXT("operator <<"); case EXP_TYPE_RSHIFT: // >> return OS_TEXT("operator >>"); case EXP_TYPE_POW: // ** return OS_TEXT("operator **"); case EXP_TYPE_ADD_ASSIGN: // += return OS_TEXT("operator +="); case EXP_TYPE_SUB_ASSIGN: // -= return OS_TEXT("operator -="); case EXP_TYPE_MUL_ASSIGN: // *= return OS_TEXT("operator *="); case EXP_TYPE_DIV_ASSIGN: // /= return OS_TEXT("operator /="); case EXP_TYPE_MOD_ASSIGN: // %= return OS_TEXT("operator %="); case EXP_TYPE_LSHIFT_ASSIGN: // <<= return OS_TEXT("operator <<="); case EXP_TYPE_RSHIFT_ASSIGN: // >>= return OS_TEXT("operator >>="); case EXP_TYPE_POW_ASSIGN: // **= return OS_TEXT("operator **="); } return OS_TEXT("unknown exp"); } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::FunctionDecl::LocalVar::LocalVar(const String& p_name): name(p_name) { start_code_pos = -1; end_code_pos = -1; } OS::Core::FunctionDecl::LocalVar::~LocalVar() { } OS::Core::FunctionDecl::FunctionDecl() // Program * p_prog) { // prog = p_prog; #ifdef OS_DEBUG prog_func_index = -1; #endif prog_parent_func_index = -1; locals = NULL; num_locals = 0; num_params = 0; max_up_count = 0; func_depth = 0; func_index = 0; num_local_funcs = 0; opcodes_pos = 0; opcodes_size = 0; } OS::Core::FunctionDecl::~FunctionDecl() { OS_ASSERT(!locals); // && !prog); } // ===================================================================== OS::Core::Program::Program(OS * allocator): filename(allocator) { this->allocator = allocator; ref_count = 1; opcodes = NULL; const_numbers = NULL; const_strings = NULL; num_numbers = 0; num_strings = 0; // gc_time = -1; } OS::Core::Program::~Program() { OS_ASSERT(ref_count == 0); int i; // values could be already destroyed by gc or will be destroyed soon allocator->free(const_numbers); const_numbers = NULL; for(i = 0; i < num_strings; i++){ OS_ASSERT(const_strings[i]->external_ref_count > 0); const_strings[i]->external_ref_count--; if(const_strings[i]->gc_color == GC_WHITE){ const_strings[i]->gc_color = GC_BLACK; } } allocator->free(const_strings); const_strings = NULL; for(i = 0; i < num_functions; i++){ FunctionDecl * func = functions + i; for(int j = 0; j < func->num_locals; j++){ func->locals[j].~LocalVar(); } allocator->free(func->locals); func->locals = NULL; // func->prog = NULL; func->~FunctionDecl(); } allocator->free(functions); functions = NULL; allocator->deleteObj(opcodes); allocator->vectorClear(debug_info); } bool OS::Core::Compiler::saveToStream(StreamWriter * writer, StreamWriter * debug_info_writer) { writer->writeBytes(OS_COMPILED_HEADER, OS_STRLEN(OS_COMPILED_HEADER)); int i, len = OS_STRLEN(OS_VERSION)+1; writer->writeByte(len); writer->writeBytes(OS_VERSION, len); MemStreamWriter int_stream(allocator); MemStreamWriter float_stream(allocator); MemStreamWriter double_stream(allocator); int int_count = 0, float_count = 0, double_count = 0; int int_index = 0, float_index = 0, double_index = 0; for(i = 0; i < prog_numbers.count; i++){ double val = prog_numbers[i]; if(val >= 0 && (double)(int)val == val){ int_count++; int_stream.writeUVariable(i - int_index); int_index = i; int_stream.writeUVariable((int)val); continue; } if((double)(float)val == val){ float_count++; float_stream.writeUVariable(i - float_index); float_index = i; float_stream.writeFloat((float)val); continue; } double_count++; double_stream.writeUVariable(i - double_index); double_index = i; double_stream.writeDouble(val); } // writer->writeUVariable(prog_numbers.count); writer->writeUVariable(int_count); writer->writeUVariable(float_count); writer->writeUVariable(double_count); writer->writeUVariable(prog_strings.count); writer->writeUVariable(prog_functions.count); writer->writeUVariable(prog_opcodes->getPos()); writer->writeBytes(int_stream.buffer.buf, int_stream.buffer.count); writer->writeBytes(float_stream.buffer.buf, float_stream.buffer.count); writer->writeBytes(double_stream.buffer.buf, double_stream.buffer.count); for(i = 0; i < prog_strings.count; i++){ const String& str = prog_strings[i]; int data_size = str.getDataSize(); writer->writeUVariable(data_size); writer->writeBytes(str.toChar(), data_size); } for(i = 0; i < prog_functions.count; i++){ Compiler::Scope * func_scope = prog_functions[i]; writer->writeUVariable(func_scope->parent ? func_scope->parent->func_index+1 : 0); // prog_functions.indexOf(func_scope->parent)); writer->writeUVariable(func_scope->num_locals); writer->writeUVariable(func_scope->num_params); writer->writeUVariable(func_scope->max_up_count); writer->writeUVariable(func_scope->func_depth); writer->writeUVariable(func_scope->func_index); writer->writeUVariable(func_scope->num_local_funcs); writer->writeUVariable(func_scope->opcodes_pos); writer->writeUVariable(func_scope->opcodes_size); OS_ASSERT(func_scope->locals_compiled.count == func_scope->num_locals); for(int j = 0; j < func_scope->locals_compiled.count; j++){ Compiler::Scope::LocalVarCompiled& var_scope = func_scope->locals_compiled[j]; OS_ASSERT(var_scope.start_code_pos >= func_scope->opcodes_pos && var_scope.start_code_pos < func_scope->opcodes_pos+func_scope->opcodes_size); OS_ASSERT(var_scope.end_code_pos > func_scope->opcodes_pos && var_scope.end_code_pos <= func_scope->opcodes_pos+func_scope->opcodes_size); writer->writeUVariable(var_scope.cached_name_index); writer->writeUVariable(var_scope.start_code_pos - func_scope->opcodes_pos); writer->writeUVariable(var_scope.end_code_pos - func_scope->opcodes_pos); } } writer->writeBytes(prog_opcodes->buffer.buf, prog_opcodes->buffer.count); if(debug_info_writer){ debug_info_writer->writeBytes(OS_DEBUGINFO_HEADER, OS_STRLEN(OS_DEBUGINFO_HEADER)); len = OS_STRLEN(OS_VERSION)+1; debug_info_writer->writeByte(len); debug_info_writer->writeBytes(OS_VERSION, len); debug_info_writer->writeUVariable(prog_debug_strings.count); debug_info_writer->writeUVariable(prog_num_debug_infos); for(i = 0; i < prog_debug_strings.count; i++){ const String& str = prog_debug_strings[i]; int data_size = str.getDataSize(); debug_info_writer->writeUVariable(data_size); debug_info_writer->writeBytes(str.toChar(), data_size); } debug_info_writer->writeBytes(prog_debug_info->buffer.buf, prog_debug_info->buffer.count); } return true; } bool OS::Core::Program::loadFromStream(StreamReader * reader, StreamReader * debuginfo_reader) { OS_ASSERT(!opcodes && !const_numbers && !num_numbers && !const_strings && !num_strings && !debug_info.count); int i, len = OS_STRLEN(OS_COMPILED_HEADER); if(!reader->checkBytes(OS_COMPILED_HEADER, len)){ return false; } len = OS_STRLEN(OS_VERSION)+1; reader->movePos(1); if(!reader->checkBytes(OS_VERSION, len)){ return false; } int int_count = reader->readUVariable(); int float_count = reader->readUVariable(); int double_count = reader->readUVariable(); num_numbers = int_count + float_count + double_count; num_strings = reader->readUVariable(); num_functions = reader->readUVariable(); int opcodes_size = reader->readUVariable(); const_numbers = (OS_NUMBER*)allocator->malloc(sizeof(OS_NUMBER) * num_numbers OS_DBG_FILEPOS); const_strings = (GCStringValue**)allocator->malloc(sizeof(GCStringValue*) * num_strings OS_DBG_FILEPOS); int num_index = 0; for(i = 0; i < int_count; i++){ num_index += reader->readUVariable(); OS_ASSERT(num_index >= 0 && num_index < num_numbers); OS_NUMBER number = (OS_NUMBER)reader->readUVariable(); const_numbers[num_index] = number; } for(num_index = 0, i = 0; i < float_count; i++){ num_index += reader->readUVariable(); OS_ASSERT(num_index >= 0 && num_index < num_numbers); OS_NUMBER number = (OS_NUMBER)reader->readFloat(); const_numbers[num_index] = number; } for(num_index = 0, i = 0; i < double_count; i++){ num_index += reader->readUVariable(); OS_ASSERT(num_index >= 0 && num_index < num_numbers); OS_NUMBER number = (OS_NUMBER)reader->readDouble(); const_numbers[num_index] = number; } StringBuffer buf(allocator); for(i = 0; i < num_strings; i++){ int data_size = reader->readUVariable(); allocator->vectorReserveCapacity(buf, data_size/sizeof(OS_CHAR) + 1 OS_DBG_FILEPOS); reader->readBytes((void*)buf.buf, data_size); buf.count = data_size/sizeof(OS_CHAR); const_strings[i] = buf.toGCStringValue(); const_strings[i]->external_ref_count++; } functions = (FunctionDecl*)allocator->malloc(sizeof(FunctionDecl) * num_functions OS_DBG_FILEPOS); for(i = 0; i < num_functions; i++){ FunctionDecl * func = functions + i; new (func) FunctionDecl(); #ifdef OS_DEBUG func->prog_func_index = i; #endif func->prog_parent_func_index = reader->readUVariable() - 1; func->num_locals = reader->readUVariable(); func->num_params = reader->readUVariable(); func->max_up_count = reader->readUVariable(); func->func_depth = reader->readUVariable(); func->func_index = reader->readUVariable(); func->num_local_funcs = reader->readUVariable(); func->opcodes_pos = reader->readUVariable(); func->opcodes_size = reader->readUVariable(); func->locals = (FunctionDecl::LocalVar*)allocator->malloc(sizeof(FunctionDecl::LocalVar) * func->num_locals OS_DBG_FILEPOS); for(int j = 0; j < func->num_locals; j++){ int cached_name_index = reader->readUVariable(); OS_ASSERT(cached_name_index >= 0 && cached_name_index < num_strings); FunctionDecl::LocalVar * local_var = func->locals + j; String var_name(const_strings[cached_name_index]); new (local_var) FunctionDecl::LocalVar(var_name); local_var->start_code_pos = reader->readUVariable() + func->opcodes_pos; local_var->end_code_pos = reader->readUVariable() + func->opcodes_pos; } } opcodes = new (allocator->malloc(sizeof(MemStreamReader) OS_DBG_FILEPOS)) MemStreamReader(allocator, opcodes_size); reader->readBytes(opcodes->buffer, opcodes_size); if(debuginfo_reader){ len = OS_STRLEN(OS_DEBUGINFO_HEADER); if(!debuginfo_reader->checkBytes(OS_DEBUGINFO_HEADER, len)){ return false; } len = OS_STRLEN(OS_VERSION)+1; debuginfo_reader->movePos(1); if(!debuginfo_reader->checkBytes(OS_VERSION, len)){ return false; } int num_strings = debuginfo_reader->readUVariable(); int num_debug_infos = debuginfo_reader->readUVariable(); Vector<String> strings; allocator->vectorReserveCapacity(strings, num_strings OS_DBG_FILEPOS); StringBuffer buf(allocator); for(i = 0; i < num_strings; i++){ int data_size = debuginfo_reader->readUVariable(); allocator->vectorReserveCapacity(buf, data_size/sizeof(OS_CHAR) + 1 OS_DBG_FILEPOS); debuginfo_reader->readBytes((void*)buf.buf, data_size); buf.count = data_size/sizeof(OS_CHAR); allocator->vectorAddItem(strings, buf.toString() OS_DBG_FILEPOS); } allocator->vectorReserveCapacity(debug_info, num_debug_infos OS_DBG_FILEPOS); for(i = 0; i < num_debug_infos; i++){ int end_opcode_offs = debuginfo_reader->readUVariable(); int line = debuginfo_reader->readUVariable(); int pos = debuginfo_reader->readUVariable(); int string_index = debuginfo_reader->readUVariable(); allocator->vectorAddItem(debug_info, DebugInfoItem(end_opcode_offs, line, pos, strings[string_index]) OS_DBG_FILEPOS); } allocator->vectorClear(strings); } return true; } OS::Core::Program::DebugInfoItem * OS::Core::Program::getDebugInfo(int opcode_pos) { Program::DebugInfoItem * info = NULL; for(int i = 0; i < debug_info.count; i++){ Program::DebugInfoItem * cur = &debug_info[i]; if(cur->opcode_pos < opcode_pos){ info = cur; } if(cur->opcode_pos > opcode_pos){ break; } } return info; } OS::Core::Program::DebugInfoItem::DebugInfoItem(int p_opcode_pos, int p_line, int p_pos, const String& p_token): token(p_token) { opcode_pos = p_opcode_pos; line = p_line; pos = p_pos; } void OS::Core::Program::pushStartFunction() { int opcode = opcodes->readByte(); if(opcode != OP_PUSH_FUNCTION){ OS_ASSERT(false); allocator->pushNull(); return; } int prog_func_index = opcodes->readUVariable(); OS_ASSERT(prog_func_index == 0); // func_index >= 0 && func_index < num_functions); FunctionDecl * func_decl = functions + prog_func_index; OS_ASSERT(func_decl->max_up_count == 0); GCFunctionValue * func_value = allocator->core->newFunctionValue(NULL, this, func_decl, allocator->core->global_vars); allocator->core->pushValue(func_value); if(filename.getDataSize()){ StringBuffer buf(allocator); buf += OS_TEXT("<<"); buf += allocator->getFilename(filename); buf += OS_TEXT(">>"); func_value->name = buf.toGCStringValue(); }else{ func_value->name = OS::String(allocator, OS_TEXT("<<CORE>>")).string; } allocator->core->gcMarkProgram(this); OS_ASSERT(func_decl->opcodes_pos == opcodes->getPos()); opcodes->movePos(func_decl->opcodes_size); } OS::Core::Program * OS::Core::Program::retain() { ref_count++; return this; } void OS::Core::Program::release() { if(--ref_count <= 0){ OS_ASSERT(ref_count == 0); OS * allocator = this->allocator; this->~Program(); allocator->free(this); } } OS::Core::Program::OpcodeType OS::Core::Program::getOpcodeType(Compiler::ExpressionType exp_type) { switch(exp_type){ case Compiler::EXP_TYPE_CALL: return OP_CALL; case Compiler::EXP_TYPE_CALL_AUTO_PARAM: return OP_CALL; // case Compiler::EXP_TYPE_GET_DIM: return OP_GET_DIM; case Compiler::EXP_TYPE_CALL_METHOD: return OP_CALL_METHOD; case Compiler::EXP_TYPE_TAIL_CALL: return OP_TAIL_CALL; case Compiler::EXP_TYPE_TAIL_CALL_METHOD: return OP_TAIL_CALL_METHOD; case Compiler::EXP_TYPE_GET_THIS: return OP_PUSH_THIS; case Compiler::EXP_TYPE_GET_ARGUMENTS: return OP_PUSH_ARGUMENTS; case Compiler::EXP_TYPE_GET_REST_ARGUMENTS: return OP_PUSH_REST_ARGUMENTS; case Compiler::EXP_TYPE_SUPER: return OP_SUPER; case Compiler::EXP_TYPE_TYPE_OF: return OP_TYPE_OF; case Compiler::EXP_TYPE_VALUE_OF: return OP_VALUE_OF; case Compiler::EXP_TYPE_NUMBER_OF: return OP_NUMBER_OF; case Compiler::EXP_TYPE_STRING_OF: return OP_STRING_OF; case Compiler::EXP_TYPE_ARRAY_OF: return OP_ARRAY_OF; case Compiler::EXP_TYPE_OBJECT_OF: return OP_OBJECT_OF; case Compiler::EXP_TYPE_USERDATA_OF: return OP_USERDATA_OF; case Compiler::EXP_TYPE_FUNCTION_OF: return OP_FUNCTION_OF; case Compiler::EXP_TYPE_LOGIC_BOOL: return OP_LOGIC_BOOL; case Compiler::EXP_TYPE_LOGIC_NOT: return OP_LOGIC_NOT; case Compiler::EXP_TYPE_BIT_NOT: return OP_BIT_NOT; case Compiler::EXP_TYPE_PLUS: return OP_PLUS; case Compiler::EXP_TYPE_NEG: return OP_NEG; case Compiler::EXP_TYPE_LENGTH: return OP_LENGTH; case Compiler::EXP_TYPE_CONCAT: return OP_CONCAT; case Compiler::EXP_TYPE_IN: return OP_IN; case Compiler::EXP_TYPE_ISPROTOTYPEOF: return OP_ISPROTOTYPEOF; case Compiler::EXP_TYPE_IS: return OP_IS; case Compiler::EXP_TYPE_LOGIC_AND: return OP_LOGIC_AND; case Compiler::EXP_TYPE_LOGIC_OR: return OP_LOGIC_OR; case Compiler::EXP_TYPE_LOGIC_PTR_EQ: return OP_LOGIC_PTR_EQ; case Compiler::EXP_TYPE_LOGIC_PTR_NE: return OP_LOGIC_PTR_NE; case Compiler::EXP_TYPE_LOGIC_EQ: return OP_LOGIC_EQ; case Compiler::EXP_TYPE_LOGIC_NE: return OP_LOGIC_NE; case Compiler::EXP_TYPE_LOGIC_GE: return OP_LOGIC_GE; case Compiler::EXP_TYPE_LOGIC_LE: return OP_LOGIC_LE; case Compiler::EXP_TYPE_LOGIC_GREATER: return OP_LOGIC_GREATER; case Compiler::EXP_TYPE_LOGIC_LESS: return OP_LOGIC_LESS; case Compiler::EXP_TYPE_BIT_AND: return OP_BIT_AND; case Compiler::EXP_TYPE_BIT_OR: return OP_BIT_OR; case Compiler::EXP_TYPE_BIT_XOR: return OP_BIT_XOR; case Compiler::EXP_TYPE_ADD: return OP_ADD; case Compiler::EXP_TYPE_SUB: return OP_SUB; case Compiler::EXP_TYPE_MUL: return OP_MUL; case Compiler::EXP_TYPE_DIV: return OP_DIV; case Compiler::EXP_TYPE_MOD: return OP_MOD; case Compiler::EXP_TYPE_LSHIFT: return OP_LSHIFT; case Compiler::EXP_TYPE_RSHIFT: return OP_RSHIFT; case Compiler::EXP_TYPE_POW: return OP_POW; } OS_ASSERT(false); return OP_UNKNOWN; } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::StreamWriter::StreamWriter(OS * p_allocator) { allocator = p_allocator; } OS::Core::StreamWriter::~StreamWriter() { } void OS::Core::StreamWriter::writeFromStream(StreamReader * reader) { int size = reader->getSize() - reader->getPos(); int buf_size = 1024 * 16; void * buf = allocator->malloc(buf_size < size ? buf_size : size OS_DBG_FILEPOS); OS_ASSERT(buf || !size); for(; size > 0; size -= buf_size){ int chunk_size = buf_size <= size ? buf_size : size; reader->readBytes(buf, chunk_size); writeBytes(buf, chunk_size); } allocator->free(buf); } void OS::Core::StreamWriter::writeByte(int value) { OS_ASSERT(value >= 0 && value <= 0xff); OS_BYTE le_value = toLittleEndianByteOrder((OS_BYTE)value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeByteAtPos(int value, int pos) { OS_ASSERT(value >= 0 && value <= 0xff); OS_BYTE le_value = toLittleEndianByteOrder((OS_BYTE)value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeUVariable(int value) { OS_ASSERT(value >= 0); for(;;){ if(value >= 0x7f){ writeByte((value & 0x7f) | 0x80); value >>= 7; }else{ writeByte(value); return; } } } void OS::Core::StreamWriter::writeU16(int value) { OS_ASSERT(value >= 0 && value <= 0xffff); OS_U16 le_value = toLittleEndianByteOrder((OS_U16)value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeU16AtPos(int value, int pos) { OS_ASSERT(value >= 0 && value <= 0xffff); OS_U16 le_value = toLittleEndianByteOrder((OS_U16)value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeInt16(int value) { OS_ASSERT((int)(OS_INT16)value == value); OS_INT16 le_value = toLittleEndianByteOrder((OS_INT16)value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeInt16AtPos(int value, int pos) { OS_ASSERT((int)(OS_INT16)value == value); OS_INT16 le_value = toLittleEndianByteOrder((OS_INT16)value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeInt32(int value) { OS_INT32 le_value = toLittleEndianByteOrder((OS_INT32)value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeInt32AtPos(int value, int pos) { OS_ASSERT((int)(OS_INT32)value == value); OS_INT32 le_value = toLittleEndianByteOrder((OS_INT32)value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeInt64(OS_INT64 value) { OS_INT64 le_value = toLittleEndianByteOrder((OS_INT64)value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeInt64AtPos(OS_INT64 value, int pos) { OS_INT64 le_value = toLittleEndianByteOrder((OS_INT64)value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeFloat(float value) { float le_value = toLittleEndianByteOrder(value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeFloatAtPos(float value, int pos) { float le_value = toLittleEndianByteOrder(value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } void OS::Core::StreamWriter::writeDouble(double value) { double le_value = toLittleEndianByteOrder(value); writeBytes(&le_value, sizeof(le_value)); } void OS::Core::StreamWriter::writeDoubleAtPos(double value, int pos) { double le_value = toLittleEndianByteOrder(value); writeBytesAtPos(&le_value, sizeof(le_value), pos); } // ===================================================================== OS::Core::MemStreamWriter::MemStreamWriter(OS * allocator): StreamWriter(allocator) { pos = 0; } OS::Core::MemStreamWriter::~MemStreamWriter() { allocator->vectorClear(buffer); } int OS::Core::MemStreamWriter::getPos() const { return pos; } void OS::Core::MemStreamWriter::setPos(int new_pos) { OS_ASSERT(new_pos >= 0 && new_pos <= buffer.count); pos = new_pos; } int OS::Core::MemStreamWriter::getSize() const { return buffer.count; } void OS::Core::MemStreamWriter::writeBytes(const void * buf, int len) { // int pos = buffer.count; allocator->vectorReserveCapacity(buffer, pos + len OS_DBG_FILEPOS); int save_pos = pos; pos += len; if(buffer.count <= pos){ buffer.count = pos; } writeBytesAtPos(buf, len, save_pos); } void OS::Core::MemStreamWriter::writeBytesAtPos(const void * buf, int len, int pos) { OS_ASSERT(pos >= 0 && pos <= buffer.count-len); OS_MEMCPY(buffer.buf+pos, buf, len); } void OS::Core::MemStreamWriter::writeByte(int value) { OS_ASSERT(value >= 0 && value <= 0xff); if(pos < buffer.count){ OS_ASSERT(pos >= 0); buffer[pos++] = (OS_BYTE)value; }else{ allocator->vectorAddItem(buffer, (OS_BYTE)value OS_DBG_FILEPOS); pos++; } } void OS::Core::MemStreamWriter::writeByteAtPos(int value, int pos) { OS_ASSERT(value >= 0 && value <= 0xff); OS_ASSERT(pos >= 0 && pos <= buffer.count-1); buffer[pos] = (OS_BYTE)value; } // ===================================================================== OS::Core::FileStreamWriter::FileStreamWriter(OS * allocator, const OS_CHAR * filename): StreamWriter(allocator) { f = allocator->openFile(filename, "wb"); } OS::Core::FileStreamWriter::~FileStreamWriter() { allocator->closeFile(f); } int OS::Core::FileStreamWriter::getPos() const { return allocator->seekFile(f, 0, SEEK_CUR); } void OS::Core::FileStreamWriter::setPos(int new_pos) { OS_ASSERT(new_pos >= 0 && new_pos <= getSize()); allocator->seekFile(f, new_pos, SEEK_SET); } int OS::Core::FileStreamWriter::getSize() const { if(f){ int save_pos = getPos(); allocator->seekFile(f, 0, SEEK_END); int size = getPos(); allocator->seekFile(f, save_pos, SEEK_SET); return size; } return 0; } void OS::Core::FileStreamWriter::writeBytes(const void * buf, int len) { allocator->writeFile(buf, len, f); } void OS::Core::FileStreamWriter::writeBytesAtPos(const void * buf, int len, int pos) { int save_pos = getPos(); allocator->seekFile(f, pos, SEEK_SET); writeBytes(buf, len); allocator->seekFile(f, save_pos, SEEK_SET); } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::StreamReader::StreamReader(OS * p_allocator) { allocator = p_allocator; } OS::Core::StreamReader::~StreamReader() { } OS_BYTE OS::Core::StreamReader::readByte() { OS_BYTE le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } OS_BYTE OS::Core::StreamReader::readByteAtPos(int pos) { OS_BYTE le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } int OS::Core::StreamReader::readUVariable() { int value = readByte(); if(!(value & 0x80)){ return value; } value &= 0x7f; for(int i = 7;; i += 7){ int b = readByte(); if(b & 0x80){ value |= (b & 0x7f) << i; }else{ OS_ASSERT((value | (b << i)) >= 0); return value | (b << i); } } return 0; // shut up compiler } OS_U16 OS::Core::StreamReader::readU16() { OS_U16 le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } OS_U16 OS::Core::StreamReader::readU16AtPos(int pos) { OS_U16 le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } OS_INT16 OS::Core::StreamReader::readInt16() { OS_INT16 le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } OS_INT16 OS::Core::StreamReader::readInt16AtPos(int pos) { OS_INT16 le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } OS_INT32 OS::Core::StreamReader::readInt32() { OS_INT32 le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } OS_INT32 OS::Core::StreamReader::readInt32AtPos(int pos) { OS_INT32 le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } OS_INT64 OS::Core::StreamReader::readInt64() { OS_INT64 le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } OS_INT64 OS::Core::StreamReader::readInt64AtPos(int pos) { OS_INT64 le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } float OS::Core::StreamReader::readFloat() { float le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } float OS::Core::StreamReader::readFloatAtPos(int pos) { float le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } double OS::Core::StreamReader::readDouble() { double le_value; readBytes(&le_value, sizeof(le_value)); return fromLittleEndianByteOrder(le_value); } double OS::Core::StreamReader::readDoubleAtPos(int pos) { double le_value; readBytesAtPos(&le_value, sizeof(le_value), pos); return fromLittleEndianByteOrder(le_value); } // ===================================================================== OS::Core::MemStreamReader::MemStreamReader(OS * allocator, int buf_size): StreamReader(allocator) { cur = buffer = (OS_BYTE*)allocator->malloc(buf_size OS_DBG_FILEPOS); size = buf_size; } OS::Core::MemStreamReader::MemStreamReader(OS * allocator, OS_BYTE * buf, int buf_size): StreamReader(allocator) { cur = buffer = buf; size = buf_size; } OS::Core::MemStreamReader::~MemStreamReader() { if(allocator){ allocator->free(buffer); } } int OS::Core::MemStreamReader::getPos() const { return cur - buffer; } void OS::Core::MemStreamReader::setPos(int new_pos) { OS_ASSERT(new_pos >= 0 && new_pos <= size); cur = buffer + new_pos; } int OS::Core::MemStreamReader::getSize() const { return size; } void OS::Core::MemStreamReader::movePos(int len) { OS_ASSERT(getPos()+len >= 0 && getPos()+len <= size); cur += len; } bool OS::Core::MemStreamReader::checkBytes(const void * src, int len) { OS_ASSERT(getPos() >= 0 && getPos()+len <= size); bool r = OS_MEMCMP(cur, src, len) == 0; cur += len; return r; } void * OS::Core::MemStreamReader::readBytes(void * dst, int len) { OS_ASSERT(getPos() >= 0 && getPos()+len <= size); OS_MEMCPY(dst, cur, len); cur += len; return dst; } void * OS::Core::MemStreamReader::readBytesAtPos(void * dst, int len, int pos) { OS_ASSERT(pos >= 0 && pos+len <= size); OS_MEMCPY(dst, buffer + pos, len); return dst; } OS_BYTE OS::Core::MemStreamReader::readByte() { OS_ASSERT(getPos() >= 0 && getPos()+(int)sizeof(OS_BYTE) <= size); return *cur++; } OS_BYTE OS::Core::MemStreamReader::readByteAtPos(int pos) { OS_ASSERT(pos >= 0 && pos+(int)sizeof(OS_BYTE) <= size); return buffer[pos]; } OS_INT32 OS::Core::MemStreamReader::readInt32() { OS_ASSERT(getPos() >= 0 && getPos()+(int)sizeof(OS_INT32) <= size); OS_BYTE * buf = cur; cur += sizeof(OS_INT32); OS_INT32 value = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); return value; } // ===================================================================== OS::Core::FileStreamReader::FileStreamReader(OS * allocator, const OS_CHAR * filename): StreamReader(allocator) { f = allocator->openFile(filename, "rb"); } OS::Core::FileStreamReader::~FileStreamReader() { allocator->closeFile(f); } int OS::Core::FileStreamReader::getPos() const { return allocator->seekFile(f, 0, SEEK_CUR); } void OS::Core::FileStreamReader::setPos(int new_pos) { OS_ASSERT(new_pos >= 0 && new_pos <= getSize()); allocator->seekFile(f, new_pos, SEEK_SET); } int OS::Core::FileStreamReader::getSize() const { if(f){ int save_pos = getPos(); allocator->seekFile(f, 0, SEEK_END); int size = getPos(); allocator->seekFile(f, save_pos, SEEK_SET); return size; } return 0; } void OS::Core::FileStreamReader::movePos(int len) { allocator->seekFile(f, len, SEEK_CUR); } bool OS::Core::FileStreamReader::checkBytes(const void * src, int len) { void * buf = alloca(len); readBytes(buf, len); return OS_MEMCMP(buf, src, len) == 0; } void * OS::Core::FileStreamReader::readBytes(void * buf, int len) { if(!f || !allocator->readFile(buf, len, f)){ OS_MEMSET(buf, 0, len); } return buf; } void * OS::Core::FileStreamReader::readBytesAtPos(void * buf, int len, int pos) { int save_pos = getPos(); allocator->seekFile(f, pos, SEEK_SET); readBytes(buf, len); allocator->seekFile(f, save_pos, SEEK_SET); return buf; } // ===================================================================== // ===================================================================== // ===================================================================== static bool isDecString(const OS_CHAR * str, int len) { OS_INT val; const OS_CHAR * end = str + len; return parseSimpleDec(str, val) && str == end; } OS::Core::PropertyIndex::PropertyIndex(const PropertyIndex& p_index): index(p_index.index) { } OS::Core::PropertyIndex::PropertyIndex(Value p_index): index(p_index) { convertIndexStringToNumber(); } OS::Core::PropertyIndex::PropertyIndex(Value p_index, const KeepStringIndex&): index(p_index) { OS_ASSERT(index.type != OS_VALUE_TYPE_STRING || PropertyIndex(p_index).index.type == OS_VALUE_TYPE_STRING); } OS::Core::PropertyIndex::PropertyIndex(GCStringValue * p_index): index(p_index) { convertIndexStringToNumber(); } OS::Core::PropertyIndex::PropertyIndex(GCStringValue * p_index, const KeepStringIndex&): index(p_index) { // OS_ASSERT(index.type != OS_VALUE_TYPE_STRING || PropertyIndex(p_index).index.type == OS_VALUE_TYPE_STRING); } OS::Core::PropertyIndex::PropertyIndex(const String& p_index): index(p_index.string) { convertIndexStringToNumber(); } OS::Core::PropertyIndex::PropertyIndex(const String& p_index, const KeepStringIndex&): index(p_index.string) { // OS_ASSERT(index.type != OS_VALUE_TYPE_STRING || PropertyIndex(p_index).index.type == OS_VALUE_TYPE_STRING); } void OS::Core::PropertyIndex::convertIndexStringToNumber() { if(index.type == OS_VALUE_TYPE_STRING){ OS_NUMBER val; const OS_CHAR * str = index.v.string->toChar(); if(*str >= OS_TEXT('0') && *str <= OS_TEXT('9')){ const OS_CHAR * end = str + index.v.string->getLen(); if(parseSimpleFloat(str, val)){ if(*str == OS_TEXT('.')){ OS_NUMBER m = (OS_NUMBER)0.1f; for(str++; *str >= OS_TEXT('0') && *str <= OS_TEXT('9'); str++, m *= (OS_NUMBER)0.1f){ val += (OS_NUMBER)(*str - OS_TEXT('0')) * m; } } if(str == end){ index.v.number = val; index.type = OS_VALUE_TYPE_NUMBER; // OS_ASSERT((OS_INT)index.v.number == val); } } } } } bool OS::Core::PropertyIndex::isEqual(const PropertyIndex& b) const { switch(index.type){ case OS_VALUE_TYPE_NULL: return b.index.type == OS_VALUE_TYPE_NULL; // case OS_VALUE_TYPE_BOOL: // return b.index.type == OS_VALUE_TYPE_BOOL && index.v.boolean == b.index.v.boolean; case OS_VALUE_TYPE_NUMBER: return b.index.type == OS_VALUE_TYPE_NUMBER && index.v.number == b.index.v.number; } return index.type == b.index.type && index.v.value == b.index.v.value; } bool OS::Core::GCStringValue::isEqual(int hash, const void * b, int size) const { return this->hash == hash && data_size == size && OS_MEMCMP(toMemory(), b, size) == 0; } bool OS::Core::GCStringValue::isEqual(int hash, const void * buf1, int size1, const void * buf2, int size2) const { if(this->hash != hash || data_size != size1 + size2){ return false; } const OS_BYTE * src = toBytes(); return OS_MEMCMP(src, buf1, size1) == 0 && (!size2 || OS_MEMCMP(src + size1, buf2, size2) == 0); } bool OS::Core::PropertyIndex::isEqual(int hash, const void * b, int size) const { if(index.type == OS_VALUE_TYPE_STRING){ return index.v.string->hash == hash && index.v.string->data_size == size && OS_MEMCMP(index.v.string->toMemory(), b, size) == 0; } return false; } bool OS::Core::PropertyIndex::isEqual(int hash, const void * buf1, int size1, const void * buf2, int size2) const { if(index.type == OS_VALUE_TYPE_STRING){ int src_size = index.v.string->data_size; if(index.v.string->hash != hash || src_size != size1 + size2){ return false; } const OS_BYTE * src = index.v.string->toBytes(); return Utils::cmp(src, size1, buf1, size1) == 0 && Utils::cmp(src + size1, size2, buf2, size2) == 0; } return false; } template <class T> int getNumberHash(T val) { return (int)val; } template <> int getNumberHash<double>(double val) { float t = (float)val; return *(int*)&t; } template <> int getNumberHash<float>(float t) { return *(int*)&t; } template <> int getNumberHash<int>(int t) { return t; } int OS::Core::PropertyIndex::getHash() const { switch(index.type){ /* case OS_VALUE_TYPE_NULL: return 0; case OS_VALUE_TYPE_BOOL: return index.v.boolean; */ case OS_VALUE_TYPE_NUMBER: #if 1 // return getNumberHash(index.v.number); { union { double d; OS_INT32 p[2]; } u; u.d = (double)index.v.number; // + 1.0f; return u.p[0] + u.p[1]; } #else /* if(sizeof(index.v.number) > sizeof(float)){ float t = (float)index.v.number; return *(int*)&t; } */ // return (int)index.v.number; OS_ASSERT(sizeof(int) <= sizeof(index.v.number)); if(IS_LITTLE_ENDIAN){ OS_U32 t = ((OS_U32*)((OS_BYTE*)&index.v.number + sizeof(index.v.number)))[-1]; return (t>>24) | (t<<8); // return ((int*)((OS_BYTE*)&index.v.number + sizeof(index.v.number)))[-1]; }else{ OS_U32 t = *(OS_U32*)&index.v.number; return (t>>24) | (t<<8); } #endif case OS_VALUE_TYPE_STRING: return index.v.string->hash; } // all other values share same area with index.v.value so just use it as hash return (ptrdiff_t) index.v.value; } // ===================================================================== OS::Core::Property::Property(const PropertyIndex& index): PropertyIndex(index) { hash_next = NULL; prev = NULL; next = NULL; } OS::Core::Property::Property(Value index): PropertyIndex(index) { hash_next = NULL; prev = NULL; next = NULL; } OS::Core::Property::Property(Value index, const KeepStringIndex& keep): PropertyIndex(index, keep) { hash_next = NULL; prev = NULL; next = NULL; } OS::Core::Property::Property(GCStringValue * index): PropertyIndex(index) { hash_next = NULL; prev = NULL; next = NULL; } OS::Core::Property::Property(GCStringValue * index, const KeepStringIndex& keep): PropertyIndex(index, keep) { hash_next = NULL; prev = NULL; next = NULL; } OS::Core::Property::~Property() { OS_ASSERT(!hash_next); OS_ASSERT(!prev); OS_ASSERT(!next); } // ===================================================================== OS::Core::Table::IteratorState::IteratorState() { table = NULL; prop = NULL; next = NULL; ascending = true; } OS::Core::Table::IteratorState::~IteratorState() { OS_ASSERT(!table && !prop && !next); } OS::Core::Table::Table() { head_mask = 0; heads = NULL; next_index = 0; count = 0; first = last = NULL; iterators = NULL; } OS::Core::Table::~Table() { OS_ASSERT(count == 0 && !first && !last && !iterators); OS_ASSERT(!heads); } bool OS::Core::Table::containsIterator(IteratorState * iter) { for(IteratorState * cur = iterators; cur; cur = cur->next){ if(cur == iter){ OS_ASSERT(iter->table == this); return true; } } OS_ASSERT(iter->table != this); return false; } void OS::Core::Table::addIterator(IteratorState * iter) { OS_ASSERT(!containsIterator(iter)); OS_ASSERT(!iter->prop && !iter->table); iter->table = this; iter->prop = iter->ascending ? first : last; iter->next = iterators; iterators = iter; } void OS::Core::Table::removeIterator(IteratorState * iter) { OS_ASSERT(containsIterator(iter)); IteratorState * prev = NULL; for(IteratorState * cur = iterators; cur; prev = cur, cur = cur->next){ if(cur == iter){ if(!prev){ iterators = cur->next; }else{ prev->next = cur->next; } cur->table = NULL; cur->next = NULL; cur->prop = NULL; return; } } OS_ASSERT(false); } OS::Core::Table * OS::Core::newTable(OS_DBG_FILEPOS_START_DECL) { return new (malloc(sizeof(Table) OS_DBG_FILEPOS_PARAM)) Table(); } void OS::Core::clearTable(Table * table) { OS_ASSERT(table); Property * prop = table->last, * prev; table->count = 0; table->first = NULL; table->last = NULL; for(; prop; prop = prev){ prev = prop->prev; prop->hash_next = NULL; prop->prev = NULL; prop->next = NULL; prop->~Property(); free(prop); } while(table->iterators){ table->removeIterator(table->iterators); } // OS_ASSERT(table->count == 0 && !table->first && !table->last); free(table->heads); table->heads = NULL; table->head_mask = 0; table->next_index = 0; } void OS::Core::deleteTable(Table * table) { OS_ASSERT(table); clearTable(table); table->~Table(); free(table); } void OS::Core::addTableProperty(Table * table, Property * prop) { OS_ASSERT(prop->next == NULL); OS_ASSERT(!table->get(*prop)); if((table->count>>HASH_GROW_SHIFT) >= table->head_mask){ int new_size = table->heads ? (table->head_mask+1) * 2 : 4; int alloc_size = sizeof(Property*)*new_size; Property ** new_heads = (Property**)malloc(alloc_size OS_DBG_FILEPOS); OS_ASSERT(new_heads); OS_MEMSET(new_heads, 0, alloc_size); Property ** old_heads = table->heads; table->heads = new_heads; table->head_mask = new_size-1; for(Property * cur = table->first; cur; cur = cur->next){ int slot = cur->getHash() & table->head_mask; cur->hash_next = table->heads[slot]; table->heads[slot] = cur; } // delete [] old_heads; free(old_heads); } int slot = prop->getHash() & table->head_mask; prop->hash_next = table->heads[slot]; table->heads[slot] = prop; if(!table->first){ table->first = prop; }else{ OS_ASSERT(table->last); table->last->next = prop; prop->prev = table->last; } table->last = prop; if(prop->index.type == OS_VALUE_TYPE_NUMBER && table->next_index <= prop->index.v.number){ table->next_index = (OS_INT)prop->index.v.number + 1; } table->count++; } void OS::Core::changePropertyIndex(Table * table, Property * prop, const PropertyIndex& new_index) { int slot = prop->getHash() & table->head_mask; Property * cur = table->heads[slot], * chain_prev = NULL; for(; cur; chain_prev = cur, cur = cur->hash_next){ if(cur == prop){ // cur->isEqual(index)){ if(chain_prev){ chain_prev->hash_next = cur->hash_next; }else{ table->heads[slot] = cur->hash_next; } break; } } OS_ASSERT(cur && cur == prop); if(cur){ *prop = new_index; slot = prop->getHash() & table->head_mask; prop->hash_next = table->heads[slot]; table->heads[slot] = prop; if(prop->index.type == OS_VALUE_TYPE_NUMBER && table->next_index <= prop->index.v.number){ table->next_index = (OS_INT)prop->index.v.number + 1; } } } OS::Core::Property * OS::Core::removeTableProperty(Table * table, const PropertyIndex& index) { OS_ASSERT(table); int slot = index.getHash() & table->head_mask; Property * cur = table->heads[slot], * chain_prev = NULL; for(; cur; chain_prev = cur, cur = cur->hash_next){ if(cur->isEqual(index)){ if(table->first == cur){ table->first = cur->next; if(table->first){ table->first->prev = NULL; } }else{ OS_ASSERT(cur->prev); cur->prev->next = cur->next; } if(table->last == cur){ table->last = cur->prev; if(table->last){ table->last->next = NULL; } }else{ OS_ASSERT(cur->next); cur->next->prev = cur->prev; } if(chain_prev){ chain_prev->hash_next = cur->hash_next; }else{ table->heads[slot] = cur->hash_next; } for(Table::IteratorState * iter = table->iterators; iter; iter = iter->next){ if(iter->prop == cur){ iter->prop = iter->ascending ? cur->next : cur->prev; } } cur->next = NULL; cur->prev = NULL; cur->hash_next = NULL; // cur->value.clear(); table->count--; return cur; } } return NULL; } bool OS::Core::deleteTableProperty(Table * table, const PropertyIndex& index) { Property * prop = removeTableProperty(table, index); if(prop){ prop->~Property(); free(prop); return true; } return false; } void OS::Core::deleteValueProperty(GCValue * table_value, const PropertyIndex& index, bool anonymous_del_enabled, bool named_del_enabled, bool prototype_enabled) { Table * table = table_value->table; if(table && deleteTableProperty(table, index)){ return; } if(1){ // prototype_enabled){ GCValue * cur_value = table_value; while(cur_value->prototype){ cur_value = cur_value->prototype; Table * cur_table = cur_value->table; if(!cur_table){ continue; } if(prototype_enabled){ if(cur_table && deleteTableProperty(cur_table, index)){ return; } }else{ if(cur_table && cur_table->get(index)){ return; } } } } if(index.index.type == OS_VALUE_TYPE_STRING && strings->syntax_prototype == index.index.v.string){ return; } if(table_value->type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<GCArrayValue*>(table_value)); GCArrayValue * arr = (GCArrayValue*)table_value; int i = (int)valueToInt(index.index); if(i >= 0 && i < arr->values.count){ allocator->vectorRemoveAtIndex(arr->values, i); } return; } if((anonymous_del_enabled || named_del_enabled) && !hasSpecialPrefix(index.index)){ Value value; if(index.index.type == OS_VALUE_TYPE_STRING && named_del_enabled){ const void * buf1 = strings->__delAt.toChar(); int size1 = strings->__delAt.getDataSize(); const void * buf2 = index.index.v.string->toChar(); int size2 = index.index.v.string->getDataSize(); GCStringValue * del_name = newStringValue(buf1, size1, buf2, size2); if(getPropertyValue(value, table_value, PropertyIndex(del_name, PropertyIndex::KeepStringIndex()), prototype_enabled) && value.isFunction()) { pushValue(value); pushValue(table_value); pushValue(index.index); call(1, 0); return; } } if(anonymous_del_enabled && getPropertyValue(value, table_value, PropertyIndex(strings->__del, PropertyIndex::KeepStringIndex()), prototype_enabled) && value.isFunction()) { pushValue(value); pushValue(table_value); pushValue(index.index); call(1, 0); } } } void OS::Core::deleteValueProperty(Value table_value, const PropertyIndex& index, bool anonymous_del_enabled, bool named_del_enabled, bool prototype_enabled) { switch(table_value.type){ case OS_VALUE_TYPE_NULL: return; case OS_VALUE_TYPE_BOOL: if(prototype_enabled){ return deleteValueProperty(prototypes[PROTOTYPE_BOOL], index, anonymous_del_enabled, named_del_enabled, prototype_enabled); } return; case OS_VALUE_TYPE_NUMBER: if(prototype_enabled){ return deleteValueProperty(prototypes[PROTOTYPE_NUMBER], index, anonymous_del_enabled, named_del_enabled, prototype_enabled); } return; case OS_VALUE_TYPE_STRING: /* if(prototype_enabled){ return deleteValueProperty(prototypes[PROTOTYPE_STRING], index, anonymous_del_enabled, named_del_enabled, prototype_enabled); } return; */ case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return deleteValueProperty(table_value.v.value, index, anonymous_del_enabled, named_del_enabled, prototype_enabled); } } void OS::Core::copyTableProperties(Table * dst, Table * src) { // OS_ASSERT(dst->count == 0); for(Property * prop = src->first; prop; prop = prop->next){ setTableValue(dst, PropertyIndex(*prop), prop->value); } } void OS::Core::copyTableProperties(GCValue * dst_value, GCValue * src_value, bool anonymous_setter_enabled, bool named_setter_enabled) { if(src_value->table){ for(Property * prop = src_value->table->first; prop; prop = prop->next){ setPropertyValue(dst_value, *prop, prop->value, anonymous_setter_enabled, named_setter_enabled); } } } void OS::Core::sortTable(Table * table, int(*comp)(OS*, const void*, const void*, void*), void * user_param, bool reorder_keys) { if(table->count > 1){ Property ** props = (Property**)malloc(sizeof(Property*) * table->count OS_DBG_FILEPOS); int i = 0; Property * cur = table->first; for(; cur && i < table->count; cur = cur->next, i++){ props[i] = cur; } OS_ASSERT(!cur && i == table->count); allocator->qsort(props, table->count, sizeof(Core::Property*), comp, user_param); table->first = props[0]; props[0]->prev = NULL; for(i = 1; i < table->count; i++){ props[i-1]->next = props[i]; props[i]->prev = props[i-1]; } props[i-1]->next = NULL; table->last = props[i-1]; if(reorder_keys){ #if 1 OS_MEMSET(table->heads, 0, sizeof(Property*)*(table->head_mask+1)); for(i = 0; i < table->count; i++){ Property * cur = props[i]; cur->index = Value(i); int slot = cur->getHash() & table->head_mask; cur->hash_next = table->heads[slot]; table->heads[slot] = cur; } #else for(i = 0; i < table->count; i++){ changePropertyIndex(table, props[i], Value(i)); } #endif table->next_index = table->count; } free(props); } } void OS::Core::sortArray(GCArrayValue * arr, int(*comp)(OS*, const void*, const void*, void*), void * user_param) { allocator->qsort(arr->values.buf, arr->values.count, sizeof(Value), comp, user_param); } static int compareResult(OS_NUMBER num) { if(num < 0) return -1; if(num > 0) return 1; return 0; } int OS::Core::comparePropValues(OS * os, const void * a, const void * b, void*) { Property * props[] = {*(Property**)a, *(Property**)b}; os->core->pushOpResultValue(Program::OP_COMPARE, props[0]->value, props[1]->value); return compareResult(os->popNumber()); } int OS::Core::comparePropValuesReverse(OS * os, const void * a, const void * b, void * user_param) { return comparePropValues(os, b, a, user_param); } int OS::Core::compareObjectProperties(OS * os, const void * a, const void * b, void * user_param) { Property * props[] = {*(Property**)a, *(Property**)b}; const String& name = *(String*)user_param; os->core->pushValue(props[0]->value); os->core->pushStringValue(name); os->getProperty(); os->core->pushValue(props[1]->value); os->core->pushStringValue(name); os->getProperty(); os->runOp(OP_COMPARE); return compareResult(os->popNumber()); } int OS::Core::compareObjectPropertiesReverse(OS * os, const void * a, const void * b, void * user_param) { return compareObjectProperties(os, b, a, user_param); } int OS::Core::compareUserPropValues(OS * os, const void * a, const void * b, void*) { Property * props[] = {*(Property**)a, *(Property**)b}; os->pushStackValue(-1); os->pushNull(); os->core->pushValue(props[0]->value); os->core->pushValue(props[1]->value); os->core->pushValue(props[0]->index); os->core->pushValue(props[1]->index); os->call(4, 1); return compareResult(os->popNumber()); } int OS::Core::compareUserPropValuesReverse(OS * os, const void * a, const void * b, void * user_param) { return compareUserPropValues(os, b, a, user_param); } int OS::Core::comparePropKeys(OS * os, const void * a, const void * b, void*) { Property * props[] = {*(Property**)a, *(Property**)b}; os->core->pushOpResultValue(Program::OP_COMPARE, props[0]->index, props[1]->index); return compareResult(os->popNumber()); } int OS::Core::comparePropKeysReverse(OS * os, const void * a, const void * b, void * user_param) { return comparePropKeys(os, b, a, user_param); } int OS::Core::compareUserPropKeys(OS * os, const void * a, const void * b, void*) { Property * props[] = {*(Property**)a, *(Property**)b}; os->pushStackValue(-1); os->pushNull(); os->core->pushValue(props[0]->index); os->core->pushValue(props[1]->index); os->core->pushValue(props[0]->value); os->core->pushValue(props[1]->value); os->call(4, 1); return compareResult(os->popNumber()); } int OS::Core::compareUserPropKeysReverse(OS * os, const void * a, const void * b, void * user_param) { return compareUserPropKeys(os, b, a, user_param); } int OS::Core::compareArrayValues(OS * os, const void * a, const void * b, void*) { Value * values[] = {(Value*)a, (Value*)b}; os->core->pushOpResultValue(Program::OP_COMPARE, *values[0], *values[1]); return compareResult(os->popNumber()); } int OS::Core::compareArrayValuesReverse(OS * os, const void * a, const void * b, void * user_param) { return compareArrayValues(os, b, a, user_param); } int OS::Core::compareUserArrayValues(OS * os, const void * a, const void * b, void*) { Value * values[] = {(Value*)a, (Value*)b}; os->pushStackValue(-1); os->pushNull(); os->core->pushValue(*values[0]); os->core->pushValue(*values[1]); os->call(2, 1); return compareResult(os->popNumber()); } int OS::Core::compareUserArrayValuesReverse(OS * os, const void * a, const void * b, void * user_param) { return compareUserArrayValues(os, b, a, user_param); } int OS::Core::compareUserReverse(OS * os, const void * a, const void * b, void * user_param) { int (*comp)(OS*, const void*, const void*, void*) = (int(*)(OS*, const void*, const void*, void*))user_param; return comp(os, b, a, NULL); } OS::Core::Property * OS::Core::Table::get(const PropertyIndex& index) { if(heads){ Property * cur = heads[index.getHash() & head_mask]; for(; cur; cur = cur->hash_next){ if(cur->isEqual(index)){ return cur; } } } return NULL; } // ===================================================================== OS::Core::GCFunctionValue::GCFunctionValue() { /* prog = NULL; func_decl = NULL; env = NULL; upvalues = NULL; */ } OS::Core::GCFunctionValue::~GCFunctionValue() { OS_ASSERT(!upvalues && !name); OS_ASSERT(!prog && !func_decl); } OS::Core::GCFunctionValue * OS::Core::newFunctionValue(StackFunction * stack_func, Program * prog, FunctionDecl * func_decl, Value env) { GCFunctionValue * func_value = new (allocator->malloc(sizeof(GCFunctionValue) OS_DBG_FILEPOS)) GCFunctionValue(); func_value->type = OS_VALUE_TYPE_FUNCTION; func_value->prototype = prototypes[PROTOTYPE_FUNCTION]; func_value->prog = prog->retain(); func_value->func_decl = func_decl; func_value->env = env; // global_vars; func_value->upvalues = stack_func ? stack_func->locals->retain() : NULL; func_value->name = NULL; registerValue(func_value); // pushValue(func_value); return func_value; } void OS::Core::clearFunctionValue(GCFunctionValue * func_value) { OS_ASSERT(func_value->prog && func_value->func_decl); // && func_data->env); // && func_data->self // value could be already destroyed by gc or will be destroyed soon // releaseValue(func_data->env); func_value->env = (GCValue*)NULL; // releaseValue(func_data->self); // func_data->self = NULL; OS_ASSERT(func_value->func_decl); if(func_value->upvalues){ releaseUpvalues(func_value->upvalues); func_value->upvalues = NULL; } func_value->name = NULL; func_value->func_decl = NULL; func_value->prog->release(); func_value->prog = NULL; // func_value->~GCFunctionValue(); // free(func_value); } // ===================================================================== /* OS::Core::Upvalues::Upvalues() { ref_count = 1; gc_time = -1; locals = NULL; is_stack_locals = false; num_locals = 0; num_params = 0; num_extra_params = 0; arguments = NULL; rest_arguments = NULL; num_parents = 0; } OS::Core::Upvalues::~Upvalues() { OS_ASSERT(!ref_count); OS_ASSERT(!locals && !arguments && !rest_arguments); } */ OS::Core::Upvalues ** OS::Core::Upvalues::getParents() { return (Upvalues**)(this + 1); } OS::Core::Upvalues * OS::Core::Upvalues::getParent(int i) { OS_ASSERT(i >= 0 && i < num_parents); return ((Upvalues**)(this+1))[i]; } OS::Core::Upvalues * OS::Core::Upvalues::retain() { ref_count++; return this; } // ===================================================================== #if 0 OS::Core::StackFunction::StackFunction() { /* func = NULL; self = NULL; locals = NULL; caller_stack_pos = 0; locals_stack_pos = 0; opcode_stack_pos = 0; bottom_stack_pos = 0; need_ret_values = 0; opcodes_offs = 0; */ } OS::Core::StackFunction::~StackFunction() { OS_ASSERT(!func && !self && !locals); } #endif // ===================================================================== OS::Core::Value::Value() { v.value = NULL; type = OS_VALUE_TYPE_NULL; } OS::Core::Value::Value(bool val) { v.boolean = val; type = OS_VALUE_TYPE_BOOL; } OS::Core::Value::Value(OS_INT32 val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; } OS::Core::Value::Value(OS_INT64 val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; } OS::Core::Value::Value(float val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; } OS::Core::Value::Value(double val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; } OS::Core::Value::Value(int val, const WeakRef&) { v.value_id = val; type = OS_VALUE_TYPE_WEAKREF; } OS::Core::Value::Value(GCValue * val) { if(val){ v.value = val; type = val->type; }else{ v.value = NULL; type = OS_VALUE_TYPE_NULL; } } OS::Core::Value& OS::Core::Value::operator=(GCValue * val) { if(val){ v.value = val; type = val->type; }else{ v.value = NULL; type = OS_VALUE_TYPE_NULL; } return *this; } OS::Core::Value& OS::Core::Value::operator=(bool val) { v.boolean = val; type = OS_VALUE_TYPE_BOOL; return *this; } OS::Core::Value& OS::Core::Value::operator=(OS_INT32 val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; return *this; } OS::Core::Value& OS::Core::Value::operator=(OS_INT64 val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; return *this; } OS::Core::Value& OS::Core::Value::operator=(float val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; return *this; } OS::Core::Value& OS::Core::Value::operator=(double val) { v.number = (OS_NUMBER)val; type = OS_VALUE_TYPE_NUMBER; return *this; } void OS::Core::Value::clear() { v.value = NULL; type = OS_VALUE_TYPE_NULL; } OS::Core::GCValue * OS::Core::Value::getGCValue() const { switch(type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: OS_ASSERT(v.value); return v.value; } return NULL; } bool OS::Core::Value::isNull() const { return type == OS_VALUE_TYPE_NULL; } bool OS::Core::Value::isFunction() const { switch(type){ case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return true; } return false; } bool OS::Core::Value::isUserdata() const { switch(type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return true; } return false; } // ===================================================================== OS::Core::ValueRetained::ValueRetained(): super() { } OS::Core::ValueRetained::ValueRetained(bool val): super(val) { // retain(); } OS::Core::ValueRetained::ValueRetained(OS_FLOAT val): super(val) { // retain(); } OS::Core::ValueRetained::ValueRetained(int val): super(val) { // retain(); } OS::Core::ValueRetained::ValueRetained(int val, const WeakRef& wr): super(val, wr) { // retain(); } OS::Core::ValueRetained::ValueRetained(GCValue * val): super(val) { // retain(); if(val){ val->external_ref_count++; } } OS::Core::ValueRetained::ValueRetained(Value b): super(b) { retain(); } OS::Core::ValueRetained::~ValueRetained() { release(); } OS::Core::ValueRetained& OS::Core::ValueRetained::operator=(Value b) { release(); super::operator=(b); retain(); return *this; } void OS::Core::ValueRetained::clear() { release(); super::clear(); } void OS::Core::ValueRetained::retain() { switch(type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: OS_ASSERT(v.value); v.value->external_ref_count++; break; } } void OS::Core::ValueRetained::release() { switch(type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: OS_ASSERT(v.value && v.value->external_ref_count > 0); v.value->external_ref_count--; if(v.value->gc_color == GC_WHITE){ v.value->gc_color = GC_BLACK; } break; } } // ===================================================================== OS::Core::GCValue::GCValue() { value_id = 0; external_ref_count = 0; hash_next = NULL; prototype = NULL; table = NULL; gc_grey_next = NULL; #ifdef OS_DEBUG gc_time = -1; #endif gc_color = GC_WHITE; type = OS_VALUE_TYPE_NULL; is_object_instance = false; } OS::Core::GCValue::~GCValue() { value_id = 0; OS_ASSERT(type == OS_VALUE_TYPE_UNKNOWN); OS_ASSERT(!table); OS_ASSERT(!hash_next); OS_ASSERT(!prototype); OS_ASSERT(gc_color != GC_GREY); } // ===================================================================== OS::Core::GCStringValue::GCStringValue(int p_data_size) { data_size = p_data_size; } OS::Core::GCStringValue * OS::Core::GCStringValue::alloc(OS * allocator, const void * buf, int data_size OS_DBG_FILEPOS_DECL) { OS_ASSERT(data_size >= 0); int alloc_size = data_size + sizeof(GCStringValue) + sizeof(wchar_t) + sizeof(wchar_t)/2; GCStringValue * string = new (allocator->malloc(alloc_size OS_DBG_FILEPOS_PARAM)) GCStringValue(data_size); string->type = OS_VALUE_TYPE_STRING; string->prototype = allocator->core->prototypes[PROTOTYPE_STRING]; OS_BYTE * data_buf = string->toBytes(); OS_MEMCPY(data_buf, buf, data_size); OS_MEMSET(data_buf + data_size, 0, sizeof(wchar_t) + sizeof(wchar_t)/2); string->calcHash(); allocator->core->registerValue(string); #ifdef OS_DEBUG string->str = string->toChar(); #endif return string; } OS::Core::GCStringValue * OS::Core::GCStringValue::alloc(OS * allocator, const void * buf1, int len1, const void * buf2, int len2 OS_DBG_FILEPOS_DECL) { OS_ASSERT(len1 >= 0 && len2 >= 0); int alloc_size = len1 + len2 + sizeof(GCStringValue) + sizeof(wchar_t) + sizeof(wchar_t)/2; GCStringValue * string = new (allocator->malloc(alloc_size OS_DBG_FILEPOS_PARAM)) GCStringValue(len1 + len2); string->type = OS_VALUE_TYPE_STRING; string->prototype = allocator->core->prototypes[PROTOTYPE_STRING]; OS_BYTE * data_buf = string->toBytes(); OS_MEMCPY(data_buf, buf1, len1); data_buf += len1; OS_MEMCPY(data_buf, buf2, len2); data_buf += len2; OS_MEMSET(data_buf, 0, sizeof(wchar_t) + sizeof(wchar_t)/2); string->calcHash(); allocator->core->registerValue(string); #ifdef OS_DEBUG string->str = string->toChar(); #endif return string; } /* OS::Core::GCStringValue * OS::Core::GCStringValue::alloc(OS * allocator, const void * buf1, int len1, const void * buf2, int len2, const void * buf3, int len3) { OS_ASSERT(len1 >= 0 && len2 >= 0 && len3 >= 0); int alloc_size = len1 + len2 + len3 + sizeof(GCStringValue) + sizeof(wchar_t) + sizeof(wchar_t)/2; GCStringValue * string = new (allocator->malloc(alloc_size)) GCStringValue(len1 + len2 + len3); string->type = OS_VALUE_TYPE_STRING; string->prototype = allocator->core->prototypes[PROTOTYPE_STRING]; OS_BYTE * data_buf = string->toBytes(); OS_MEMCPY(data_buf, buf1, len1); data_buf += len1; OS_MEMCPY(data_buf, buf2, len2); data_buf += len2; OS_MEMCPY(data_buf, buf3, len3); data_buf += len3; OS_MEMSET(data_buf, 0, sizeof(wchar_t) + sizeof(wchar_t)/2); string->calcHash(); allocator->core->registerValue(string); return string; } */ OS::Core::GCStringValue * OS::Core::GCStringValue::alloc(OS * allocator, GCStringValue * a, GCStringValue * b OS_DBG_FILEPOS_DECL) { return alloc(allocator, a->toMemory(), a->data_size, b->toMemory(), b->data_size OS_DBG_FILEPOS_PARAM); } /* OS::Core::GCStringValue * OS::Core::GCStringValue::alloc(OS * allocator, GCStringValue * a, GCStringValue * b, GCStringValue * c) { return alloc(allocator, a->toMemory(), a->data_size, b->toMemory(), b->data_size, c->toMemory(), c->data_size); } */ bool OS::Core::GCStringValue::isNumber(OS_NUMBER* p_val) const { const OS_CHAR * str = toChar(); const OS_CHAR * end = str + getLen(); OS_FLOAT val; if(Utils::parseFloat(str, val) && (str == end || (*str==OS_TEXT('f') && str+1 == end))){ if(p_val) *p_val = (OS_NUMBER)val; return true; } if(p_val) *p_val = 0; return false; } int OS::Core::GCStringValue::cmp(GCStringValue * string) const { if(this == string){ return 0; } return Utils::cmp(toBytes(), data_size, string->toBytes(), string->data_size); } int OS::Core::GCStringValue::cmp(const OS_CHAR * str) const { return cmp(str, OS_STRLEN(str)); } int OS::Core::GCStringValue::cmp(const OS_CHAR * str, int len) const { return Utils::cmp(toBytes(), data_size, str, len * sizeof(OS_CHAR)); } void OS::Core::GCStringValue::calcHash() { hash = Utils::keyToHash(toBytes(), data_size); } // ===================================================================== bool OS::Core::valueToBool(Value val) { switch(val.type){ case OS_VALUE_TYPE_NULL: return false; case OS_VALUE_TYPE_BOOL: return val.v.boolean ? true : false; case OS_VALUE_TYPE_NUMBER: // return val->value.number && !OS_ISNAN(val->value.number); return !OS_ISNAN((OS_FLOAT)val.v.number); // case OS_VALUE_TYPE_STRING: // return val->value.string_data->data_size > 0; // case OS_VALUE_TYPE_OBJECT: // case OS_VALUE_TYPE_ARRAY: // return val->table ? val->table->count : 0; } return true; } OS_INT OS::Core::valueToInt(Value val, bool valueof_enabled) { return (OS_INT)valueToNumber(val, valueof_enabled); } OS_INT OS::Core::Compiler::Expression::toInt() { return (OS_INT)toNumber(); } OS_NUMBER OS::Core::Compiler::Expression::toNumber() { switch(type){ case EXP_TYPE_CONST_NULL: return 0; case EXP_TYPE_CONST_STRING: return token->str.toNumber(); case EXP_TYPE_CONST_NUMBER: return (OS_NUMBER)token->getFloat(); case EXP_TYPE_CONST_TRUE: return 1; case EXP_TYPE_CONST_FALSE: return 0; } OS_ASSERT(false); return 0; } OS_NUMBER OS::Core::valueToNumber(Value val, bool valueof_enabled) { switch(val.type){ case OS_VALUE_TYPE_NULL: return 0; // nan_float; case OS_VALUE_TYPE_BOOL: return (OS_NUMBER)val.v.boolean; case OS_VALUE_TYPE_NUMBER: return val.v.number; case OS_VALUE_TYPE_STRING: { OS_NUMBER fval; if(val.v.string->isNumber(&fval)){ return fval; } return 0; // nan_float; } } if(valueof_enabled){ pushValueOf(val); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {this}; return valueToNumber(stack_values.lastElement(), false); } return 0; } bool OS::Core::isValueNumber(Value val, OS_NUMBER * out) { switch(val.type){ /* case OS_VALUE_TYPE_NULL: if(out){ *out = 0; } return true; */ case OS_VALUE_TYPE_BOOL: if(out){ *out = (OS_NUMBER)val.v.boolean; } return true; case OS_VALUE_TYPE_NUMBER: if(out){ *out = (OS_NUMBER)val.v.number; } return true; case OS_VALUE_TYPE_STRING: return val.v.string->isNumber(out); } if(out){ *out = 0; } return false; } OS::Core::String OS::Core::Compiler::Expression::toString() { switch(type){ case EXP_TYPE_CONST_NULL: // return String(getAllocator()); return String(getAllocator(), OS_TEXT("null")); case EXP_TYPE_CONST_STRING: return token->str; case EXP_TYPE_CONST_NUMBER: // OS_ASSERT(token->str.toFloat() == token->getFloat()); // return token->str; return String(getAllocator(), token->getFloat()); case EXP_TYPE_CONST_TRUE: // return String(getAllocator(), OS_TEXT("1")); return String(getAllocator(), OS_TEXT("true")); case EXP_TYPE_CONST_FALSE: // return String(getAllocator()); return String(getAllocator(), OS_TEXT("false")); } OS_ASSERT(false); return String(getAllocator()); } OS::Core::String OS::Core::valueToString(Value val, bool valueof_enabled) { switch(val.type){ case OS_VALUE_TYPE_NULL: // return String(allocator); return strings->syntax_null; case OS_VALUE_TYPE_BOOL: // return val->value.boolean ? String(allocator, OS_TEXT("1")) : String(allocator); return val.v.boolean ? strings->syntax_true : strings->syntax_false; case OS_VALUE_TYPE_NUMBER: return String(allocator, val.v.number, OS_AUTO_PRECISION); case OS_VALUE_TYPE_STRING: return String(val.v.string); } if(valueof_enabled){ /* Value * func = getPropertyValue(val, PropertyIndex(strings->__tostring, PropertyIndex::KeepStringIndex()), prototype_enabled); if(func){ pushValue(func); pushValue(val); call(0, 1); OS_ASSERT(stack_values.count > 0); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {this}; return valueToString(stack_values.lastElement(), false); } */ pushValueOf(val); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {this}; return valueToString(stack_values.lastElement(), false); } return String(allocator); } bool OS::Core::isValueString(Value val, String * out) { switch(val.type){ case OS_VALUE_TYPE_NULL: if(out){ // *out = String(allocator); *out = strings->syntax_null; } return false; case OS_VALUE_TYPE_BOOL: if(out){ // *out = String(allocator, val->value.boolean ? OS_TEXT("1") : OS_TEXT("")); *out = val.v.boolean ? strings->syntax_true : strings->syntax_false; } return true; case OS_VALUE_TYPE_NUMBER: if(out){ *out = String(allocator, val.v.number, OS_AUTO_PRECISION); } return true; case OS_VALUE_TYPE_STRING: if(out){ *out = String(val.v.string); } return true; // case OS_VALUE_TYPE_OBJECT: // case OS_VALUE_TYPE_ARRAY: // return String(this, (OS_INT)(val->table ? val->table->count : 0)); } if(out){ *out = String(allocator); } return false; } bool OS::Core::isValueString(Value val, OS::String * out) { switch(val.type){ case OS_VALUE_TYPE_NULL: if(out){ // *out = String(allocator); *out = strings->syntax_null; } return false; case OS_VALUE_TYPE_BOOL: if(out){ // *out = String(allocator, val->value.boolean ? OS_TEXT("1") : OS_TEXT("")); *out = val.v.boolean ? strings->syntax_true : strings->syntax_false; } return true; case OS_VALUE_TYPE_NUMBER: if(out){ *out = String(allocator, val.v.number, OS_AUTO_PRECISION); } return true; case OS_VALUE_TYPE_STRING: if(out){ *out = String(val.v.string); } return true; // case OS_VALUE_TYPE_OBJECT: // case OS_VALUE_TYPE_ARRAY: // return String(this, (OS_INT)(val->table ? val->table->count : 0)); } if(out){ *out = String(allocator); } return false; } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::StringRefs::StringRefs() { head_mask = 0; heads = NULL; count = 0; } OS::Core::StringRefs::~StringRefs() { OS_ASSERT(count == 0); OS_ASSERT(!heads); } void OS::Core::registerStringRef(StringRef * str_ref) { if((string_refs.count>>HASH_GROW_SHIFT) >= string_refs.head_mask){ int new_size = string_refs.heads ? (string_refs.head_mask+1) * 2 : 32; int alloc_size = sizeof(StringRef*) * new_size; StringRef ** new_heads = (StringRef**)malloc(alloc_size OS_DBG_FILEPOS); OS_ASSERT(new_heads); OS_MEMSET(new_heads, 0, alloc_size); StringRef ** old_heads = string_refs.heads; int old_mask = string_refs.head_mask; string_refs.heads = new_heads; string_refs.head_mask = new_size-1; if(old_heads){ for(int i = 0; i <= old_mask; i++){ for(StringRef * str_ref = old_heads[i], * next; str_ref; str_ref = next){ next = str_ref->hash_next; int slot = str_ref->string_hash & string_refs.head_mask; str_ref->hash_next = string_refs.heads[slot]; string_refs.heads[slot] = str_ref; } } free(old_heads); } } int slot = str_ref->string_hash & string_refs.head_mask; str_ref->hash_next = string_refs.heads[slot]; string_refs.heads[slot] = str_ref; string_refs.count++; } void OS::Core::unregisterStringRef(StringRef * str_ref) { int slot = str_ref->string_hash & string_refs.head_mask; StringRef * cur = string_refs.heads[slot], * prev = NULL; for(; cur; prev = cur, cur = cur->hash_next){ if(cur == str_ref){ if(prev){ prev->hash_next = cur->hash_next; }else{ string_refs.heads[slot] = cur->hash_next; } OS_ASSERT(string_refs.count > 0); string_refs.count--; cur->hash_next = NULL; return; } } OS_ASSERT(false); } void OS::Core::deleteStringRefs() { if(!string_refs.count){ return; } for(int i = 0; i <= string_refs.head_mask; i++){ while(string_refs.heads[i]){ StringRef * cur = string_refs.heads[i]; string_refs.heads[i] = cur->hash_next; free(cur); } } free(string_refs.heads); string_refs.heads = NULL; string_refs.head_mask = 0; string_refs.count = 0; } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::Values::Values() { head_mask = 0; // OS_DEF_VALUES_HASH_SIZE-1; heads = NULL; // new Value*[OS_DEF_VALUES_HASH_SIZE]; // OS_ASSERT(heads); next_id = 1; count = 0; } OS::Core::Values::~Values() { OS_ASSERT(count == 0); OS_ASSERT(!heads); // delete [] heads; } void OS::Core::registerValue(GCValue * value) { value->value_id = values.next_id++; if((values.count>>HASH_GROW_SHIFT) >= values.head_mask){ int new_size = values.heads ? (values.head_mask+1) * 2 : 32; int alloc_size = sizeof(GCValue*) * new_size; GCValue ** new_heads = (GCValue**)malloc(alloc_size OS_DBG_FILEPOS); // new Value*[new_size]; OS_ASSERT(new_heads); OS_MEMSET(new_heads, 0, alloc_size); GCValue ** old_heads = values.heads; int old_mask = values.head_mask; values.heads = new_heads; values.head_mask = new_size-1; if(old_heads){ for(int i = 0; i <= old_mask; i++){ for(GCValue * value = old_heads[i], * next; value; value = next){ gcAddToGreyList(value); next = value->hash_next; int slot = value->value_id & values.head_mask; value->hash_next = values.heads[slot]; values.heads[slot] = value; } } // delete [] old_heads; free(old_heads); } if(gc_values_head_index >= 0){ // restart gc ASAP gc_values_head_index = -1; gc_start_next_values = 0; gc_continuous = false; gc_step_size_auto_mult *= 4.0f; } } int slot = value->value_id & values.head_mask; value->hash_next = values.heads[slot]; values.heads[slot] = value; values.count++; num_created_values++; gcAddToGreyList(value); // value->gc_color = GC_BLACK; gcStepIfNeeded(); } OS::Core::GCValue * OS::Core::unregisterValue(int value_id) { int slot = value_id & values.head_mask; GCValue * value = values.heads[slot], * prev = NULL; for(; value; prev = value, value = value->hash_next){ if(value->value_id == value_id){ if(prev){ prev->hash_next = value->hash_next; }else{ values.heads[slot] = value->hash_next; } OS_ASSERT(values.count > 0); values.count--; value->hash_next = NULL; return value; } } return NULL; } void OS::Core::deleteValues(bool del_ref_counted_also) { if(values.heads && values.count > 0){ while(true){ for(int i = 0; i <= values.head_mask; i++){ #if 0 for(GCValue * value; value = values.heads[i]; ){ deleteValue(value); } #else for(GCValue * value = values.heads[i], * next; value; value = next){ next = value->hash_next; if(del_ref_counted_also || !value->external_ref_count){ deleteValue(value); } } #endif } if(!values.count || !del_ref_counted_also){ break; } } } if(values.heads && values.count == 0){ free(values.heads); values.heads = NULL; values.head_mask = 0; values.next_id = 1; } } OS::Core::GCValue * OS::Core::Values::get(int value_id) { int slot = value_id & head_mask; for(GCValue * value = heads[slot]; value; value = value->hash_next){ if(value->value_id == value_id){ return value; } } return NULL; } // ===================================================================== // ===================================================================== // ===================================================================== OS::Core::Strings::Strings(OS * allocator) : __construct(allocator, OS_TEXT("__construct")), // __destruct(allocator, OS_TEXT("__destruct")), __object(allocator, OS_TEXT("__object")), __get(allocator, OS_TEXT("__get")), __set(allocator, OS_TEXT("__set")), __getAt(allocator, OS_TEXT("__get@")), __setAt(allocator, OS_TEXT("__set@")), __del(allocator, OS_TEXT("__del")), __delAt(allocator, OS_TEXT("__del@")), __getempty(allocator, OS_TEXT("__getempty")), __setempty(allocator, OS_TEXT("__setempty")), __delempty(allocator, OS_TEXT("__delempty")), __getdim(allocator, OS_TEXT("__getdim")), __setdim(allocator, OS_TEXT("__setdim")), __deldim(allocator, OS_TEXT("__deldim")), __cmp(allocator, OS_TEXT("__cmp")), __iter(allocator, OS_TEXT("__iter")), // __tostring(allocator, OS_TEXT("__tostring")), __valueof(allocator, OS_TEXT("__valueof")), /* __booleanof(allocator, OS_TEXT("__booleanof")), __numberof(allocator, OS_TEXT("__numberof")), __stringof(allocator, OS_TEXT("__stringof")), __arrayof(allocator, OS_TEXT("__arrayof")), __objectof(allocator, OS_TEXT("__objectof")), __userdataof(allocator, OS_TEXT("__userdataof")), __functionof(allocator, OS_TEXT("__functionof")), */ __clone(allocator, OS_TEXT("__clone")), __concat(allocator, OS_TEXT("__concat")), __bitand(allocator, OS_TEXT("__bitand")), __bitor(allocator, OS_TEXT("__bitor")), __bitxor(allocator, OS_TEXT("__bitxor")), __bitnot(allocator, OS_TEXT("__bitnot")), __plus(allocator, OS_TEXT("__plus")), __neg(allocator, OS_TEXT("__neg")), __len(allocator, OS_TEXT("__len")), __add(allocator, OS_TEXT("__add")), __sub(allocator, OS_TEXT("__sub")), __mul(allocator, OS_TEXT("__mul")), __div(allocator, OS_TEXT("__div")), __mod(allocator, OS_TEXT("__mod")), __lshift(allocator, OS_TEXT("__lshift")), __rshift(allocator, OS_TEXT("__rshift")), __pow(allocator, OS_TEXT("__pow")), typeof_null(allocator, OS_TEXT("null")), typeof_boolean(allocator, OS_TEXT("boolean")), typeof_number(allocator, OS_TEXT("number")), typeof_string(allocator, OS_TEXT("string")), typeof_object(allocator, OS_TEXT("object")), typeof_array(allocator, OS_TEXT("array")), typeof_userdata(allocator, OS_TEXT("userdata")), typeof_function(allocator, OS_TEXT("function")), syntax_get(allocator, OS_TEXT("get")), syntax_set(allocator, OS_TEXT("set")), syntax_super(allocator, OS_TEXT("super")), syntax_is(allocator, OS_TEXT("is")), syntax_isprototypeof(allocator, OS_TEXT("isprototypeof")), syntax_typeof(allocator, OS_TEXT("typeof")), syntax_valueof(allocator, OS_TEXT("valueof")), syntax_booleanof(allocator, OS_TEXT("booleanof")), syntax_numberof(allocator, OS_TEXT("numberof")), syntax_stringof(allocator, OS_TEXT("stringof")), syntax_arrayof(allocator, OS_TEXT("arrayof")), syntax_objectof(allocator, OS_TEXT("objectof")), syntax_userdataof(allocator, OS_TEXT("userdataof")), syntax_functionof(allocator, OS_TEXT("functionof")), syntax_extends(allocator, OS_TEXT("extends")), syntax_clone(allocator, OS_TEXT("clone")), syntax_delete(allocator, OS_TEXT("delete")), syntax_prototype(allocator, OS_TEXT("prototype")), syntax_var(allocator, OS_TEXT("var")), syntax_this(allocator, OS_TEXT("this")), syntax_arguments(allocator, OS_TEXT("arguments")), syntax_function(allocator, OS_TEXT("function")), syntax_null(allocator, OS_TEXT("null")), syntax_true(allocator, OS_TEXT("true")), syntax_false(allocator, OS_TEXT("false")), syntax_return(allocator, OS_TEXT("return")), syntax_class(allocator, OS_TEXT("class")), syntax_enum(allocator, OS_TEXT("enum")), syntax_switch(allocator, OS_TEXT("switch")), syntax_case(allocator, OS_TEXT("case")), syntax_default(allocator, OS_TEXT("default")), syntax_if(allocator, OS_TEXT("if")), syntax_else(allocator, OS_TEXT("else")), syntax_elseif(allocator, OS_TEXT("elseif")), syntax_for(allocator, OS_TEXT("for")), syntax_in(allocator, OS_TEXT("in")), syntax_break(allocator, OS_TEXT("break")), syntax_continue(allocator, OS_TEXT("continue")), syntax_debugger(allocator, OS_TEXT("debugger")), syntax_debuglocals(allocator, OS_TEXT("debuglocals")), #ifdef OS_GLOBAL_VAR_ENABLED var_globals(allocator, OS_GLOBALS_VAR_NAME), #endif var_env(allocator, OS_ENV_VAR_NAME), __dummy__(0) { } // ===================================================================== // ===================================================================== // ===================================================================== OS::MemoryManager::MemoryManager() { ref_count = 1; } OS::MemoryManager::~MemoryManager() { } OS::MemoryManager * OS::MemoryManager::retain() { ref_count++; return this; } void OS::MemoryManager::release() { if(--ref_count <= 0){ OS_ASSERT(ref_count == 0); delete this; } } bool OS::isFileExist(const OS_CHAR * filename) { void * f = openFile(filename, "rb"); if(f){ closeFile(f); return true; } return false; } void * OS::openFile(const OS_CHAR * filename, const OS_CHAR * mode)\ { return fopen(filename, mode); } int OS::readFile(void * buf, int size, void * f) { if(f){ return fread(buf, size, 1, (FILE*)f); } return 0; } int OS::writeFile(const void * buf, int size, void * f) { if(f){ return fwrite(buf, size, 1, (FILE*)f); } return 0; } int OS::seekFile(void * f, int offset, int whence) { if(f){ fseek((FILE*)f, offset, whence); return ftell((FILE*)f); } return 0; } void OS::closeFile(void * f) { if(f){ fclose((FILE*)f); } } void OS::printf(const OS_CHAR * format, ...) { va_list va; va_start(va, format); OS_VPRINTF(format, va); va_end(va); } OS::SmartMemoryManager::SmartMemoryManager() { allocated_bytes = 0; max_allocated_bytes = 0; cached_bytes = 0; OS_MEMSET(page_desc, 0, sizeof(page_desc)); num_page_desc = 0; OS_MEMSET(pages, 0, sizeof(pages)); OS_MEMSET(cached_blocks, 0, sizeof(cached_blocks)); #ifdef OS_DEBUG dbg_mem_list = NULL; dbg_std_mem_list = NULL; dbg_breakpoint_id = -1; #endif stat_malloc_count = 0; stat_free_count = 0; registerPageDesc(sizeof(Core::GCObjectValue), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::GCStringValue), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::GCUserdataValue), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::GCFunctionValue), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::GCCFunctionValue), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::GCCFunctionValue) + sizeof(Core::Value)*4, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Property), OS_MEMORY_MANAGER_PAGE_BLOCKS); // registerPageDesc(sizeof(Core::StackFunction), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Upvalues), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Upvalues) + sizeof(void*)*4, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Upvalues) + sizeof(void*)*8, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Table), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::Compiler::EXPRESSION_SIZE), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(sizeof(Core::TokenData), OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(8, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(16, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(32, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(64, OS_MEMORY_MANAGER_PAGE_BLOCKS); registerPageDesc(128, OS_MEMORY_MANAGER_PAGE_BLOCKS/2); registerPageDesc(256, OS_MEMORY_MANAGER_PAGE_BLOCKS/4); sortPageDesc(); } OS::SmartMemoryManager::~SmartMemoryManager() { freeCachedMemory(0); #ifdef OS_DEBUG { for(MemBlock * mem = dbg_mem_list; mem; mem = mem->dbg_mem_next){ OS_PRINTF("[LEAK] %d bytes, id: %d, line %d, %s\n", mem->block_size, mem->dbg_id, mem->dbg_line, mem->dbg_filename); } } { for(StdMemBlock * mem = dbg_std_mem_list; mem; mem = mem->dbg_mem_next){ OS_ASSERT(mem->block_size & 0x80000000); OS_PRINTF("[LEAK] %d bytes, id: %d, line %d, %s\n", (mem->block_size & ~0x80000000), mem->dbg_id, mem->dbg_line, mem->dbg_filename); } } #endif // OS_ASSERT(!allocated_bytes && !cached_bytes); } #ifdef OS_DEBUG static const int MEM_MARK_BEGIN = 0xabcdef98; static const int MEM_MARK_END = 0x3579faec; static const int FREE_MARK_BEGIN = 0xdabcef98; static const int FREE_MARK_END = 0x3faec579; static const int STD_MEM_MARK_BEGIN = 0xaefbcd98; static const int STD_MEM_MARK_END = 0x35ae79fc; #define MEM_MARK_END_SIZE sizeof(int) #else #define MEM_MARK_END_SIZE 0 #endif int OS::SmartMemoryManager::comparePageDesc(const void * pa, const void * pb) { PageDesc * a = (PageDesc*)pa; PageDesc * b = (PageDesc*)pb; return a->block_size - b->block_size; } void OS::SmartMemoryManager::sortPageDesc() { ::qsort(page_desc, num_page_desc, sizeof(page_desc[0]), comparePageDesc); } void OS::SmartMemoryManager::registerPageDesc(int block_size, int num_blocks) { if(num_page_desc == MAX_PAGE_TYPE_COUNT){ return; } if(block_size > 128){ block_size = (block_size + 31) & ~31; }else if(block_size > 64){ block_size = (block_size + 15) & ~15; }else if(block_size > 32){ block_size = (block_size + 7) & ~7; }else{ block_size = (block_size + 3) & ~3; } int i; for(i = 0; i < num_page_desc; i++){ if(page_desc[i].block_size == block_size){ if(page_desc[i].num_blocks < num_blocks){ page_desc[i].num_blocks = num_blocks; page_desc[i].allocated_bytes = sizeof(Page) + (sizeof(MemBlock) + block_size + MEM_MARK_END_SIZE) * num_blocks; } return; } } page_desc[i].block_size = block_size; page_desc[i].num_blocks = num_blocks; page_desc[i].allocated_bytes = sizeof(Page) + (sizeof(MemBlock) + block_size + MEM_MARK_END_SIZE) * num_blocks; num_page_desc++; } void * OS::SmartMemoryManager::allocFromCachedBlock(int i OS_DBG_FILEPOS_DECL) { #ifdef OS_DEBUG if(stat_malloc_count == dbg_breakpoint_id){ DEBUG_BREAK; } #endif stat_malloc_count++; OS_ASSERT(i >= 0 && i < num_page_desc); CachedBlock * cached_block = cached_blocks[i]; OS_ASSERT(cached_block); #ifdef OS_DEBUG OS_ASSERT(cached_block->mark == FREE_MARK_BEGIN); OS_ASSERT(*(int*)(((OS_BYTE*)((MemBlock*)cached_block+1)) + page_desc[i].block_size) == FREE_MARK_END); #endif cached_blocks[i] = cached_block->next; Page * page = cached_block->page; OS_ASSERT(page->num_cached_blocks > 0); page->num_cached_blocks--; MemBlock * mem_block = (MemBlock*)cached_block; mem_block->page = page; mem_block->block_size = page_desc[i].block_size; #ifdef OS_DEBUG mem_block->mark = MEM_MARK_BEGIN; *(int*)(((OS_BYTE*)(mem_block+1)) + mem_block->block_size) = MEM_MARK_END; mem_block->dbg_filename = dbg_filename; mem_block->dbg_line = dbg_line; mem_block->dbg_id = stat_malloc_count-1; mem_block->dbg_mem_prev = NULL; mem_block->dbg_mem_next = dbg_mem_list; if(dbg_mem_list){ dbg_mem_list->dbg_mem_prev = mem_block; } dbg_mem_list = mem_block; #endif cached_bytes -= mem_block->block_size + sizeof(MemBlock); void * p = mem_block + 1; OS_MEMSET(p, 0, mem_block->block_size); // OS_ASSERT(mem_block->mark == MEM_MARK_BEGIN); // OS_ASSERT(*(int*)(((OS_BYTE*)(mem_block+1)) + mem_block->block_size) == MEM_MARK_END); return p; } void * OS::SmartMemoryManager::allocFromPageType(int i OS_DBG_FILEPOS_DECL) { OS_ASSERT(i >= 0 && i < num_page_desc); if(cached_blocks[i]){ return allocFromCachedBlock(i OS_DBG_FILEPOS_PARAM); } int allocated_bytes = page_desc[i].allocated_bytes; Page * page = (Page*)stdAlloc(allocated_bytes OS_DBG_FILEPOS); page->index = i; page->next_page = pages[i]; pages[i] = page; page->num_cached_blocks = page_desc[i].num_blocks; cached_bytes += allocated_bytes; OS_BYTE * next_page_block = (OS_BYTE*)(page + 1); for(int j = 0; j < page_desc[i].num_blocks; j++){ CachedBlock * cached_block = (CachedBlock*)next_page_block; cached_block->page = page; cached_block->next = cached_blocks[i]; #ifdef OS_DEBUG cached_block->mark = FREE_MARK_BEGIN; *(int*)(((OS_BYTE*)((MemBlock*)cached_block+1)) + page_desc[page->index].block_size) = FREE_MARK_END; OS_MEMSET(cached_block+1, 0xde, page_desc[i].block_size + (sizeof(MemBlock) - sizeof(CachedBlock))); #endif cached_blocks[i] = cached_block; next_page_block += sizeof(MemBlock) + page_desc[i].block_size + MEM_MARK_END_SIZE; } return allocFromCachedBlock(i OS_DBG_FILEPOS_PARAM); } void OS::SmartMemoryManager::freeMemBlock(MemBlock * mem_block) { stat_free_count++; #ifdef OS_DEBUG OS_ASSERT(mem_block->mark == MEM_MARK_BEGIN); OS_ASSERT(*(int*)(((OS_BYTE*)(mem_block+1)) + mem_block->block_size) == MEM_MARK_END); if(mem_block->dbg_id == dbg_breakpoint_id){ DEBUG_BREAK; } if(mem_block == dbg_mem_list){ OS_ASSERT(!mem_block->dbg_mem_prev); dbg_mem_list = mem_block->dbg_mem_next; }else{ // if(mem_block->dbg_mem_prev){ OS_ASSERT(mem_block->dbg_mem_prev); mem_block->dbg_mem_prev->dbg_mem_next = mem_block->dbg_mem_next; } if(mem_block->dbg_mem_next){ mem_block->dbg_mem_next->dbg_mem_prev = mem_block->dbg_mem_prev; } #endif Page * page = mem_block->page; int size = mem_block->block_size; cached_bytes += size + sizeof(MemBlock); CachedBlock * cached_block = (CachedBlock*)mem_block; cached_block->page = page; cached_block->next = cached_blocks[page->index]; #ifdef OS_DEBUG cached_block->mark = FREE_MARK_BEGIN; *(int*)(((OS_BYTE*)((MemBlock*)cached_block+1)) + page_desc[page->index].block_size) = FREE_MARK_END; OS_MEMSET(cached_block+1, 0xde, size + (sizeof(MemBlock) - sizeof(CachedBlock))); #endif cached_blocks[page->index] = cached_block; page->num_cached_blocks++; } void OS::SmartMemoryManager::freeCachedMemory(int new_cached_bytes) { if(cached_bytes > new_cached_bytes){ for(int i = num_page_desc-1; i >= 0; i--){ bool found_free_page = false; int num_blocks = page_desc[i].num_blocks; CachedBlock * prev_cached_block = NULL, * next_cached_block = NULL; for(CachedBlock * cached_block = cached_blocks[i]; cached_block; cached_block = next_cached_block){ OS_ASSERT(cached_block->page->index == i); next_cached_block = cached_block->next; if(cached_block->page->num_cached_blocks == num_blocks){ found_free_page = true; if(!prev_cached_block){ cached_blocks[i] = next_cached_block; }else{ prev_cached_block->next = next_cached_block; } // keep prev_cached_block continue; } prev_cached_block = cached_block; } if(found_free_page){ Page * prev = NULL, * next; for(Page * page = pages[i]; page; page = next){ next = page->next_page; if(page->num_cached_blocks == num_blocks){ if(!prev){ pages[i] = page->next_page; }else{ prev->next_page = page->next_page; } cached_bytes -= page_desc[i].allocated_bytes; stdFree(page); // stat_free_count++; }else{ prev = page; } } if(cached_bytes <= new_cached_bytes){ break; } } } } } void * OS::SmartMemoryManager::stdAlloc(int size OS_DBG_FILEPOS_DECL) { #ifdef OS_DEBUG if(stat_malloc_count == dbg_breakpoint_id){ DEBUG_BREAK; } #endif stat_malloc_count++; size = (size + 7) & ~7; StdMemBlock * mem_block = (StdMemBlock*)::malloc(size + sizeof(StdMemBlock) + MEM_MARK_END_SIZE); if(!mem_block && cached_bytes > 0){ freeCachedMemory(0); mem_block = (StdMemBlock*)::malloc(size + sizeof(StdMemBlock) + MEM_MARK_END_SIZE); if(!mem_block){ return NULL; } } #ifdef OS_DEBUG mem_block->mark = STD_MEM_MARK_BEGIN; *(int*)(((OS_BYTE*)(mem_block+1)) + size) = STD_MEM_MARK_END; mem_block->dbg_filename = dbg_filename; mem_block->dbg_line = dbg_line; mem_block->dbg_id = stat_malloc_count-1; mem_block->dbg_mem_prev = NULL; mem_block->dbg_mem_next = dbg_std_mem_list; if(dbg_std_mem_list){ dbg_std_mem_list->dbg_mem_prev = mem_block; } dbg_std_mem_list = mem_block; #endif mem_block->block_size = size | 0x80000000; allocated_bytes += size + sizeof(StdMemBlock) + MEM_MARK_END_SIZE; if(max_allocated_bytes < allocated_bytes){ max_allocated_bytes = allocated_bytes; } OS_MEMSET(mem_block+1, 0, size); return mem_block+1; } void OS::SmartMemoryManager::stdFree(void * ptr) { stat_free_count++; StdMemBlock * mem_block = (StdMemBlock*)ptr - 1; OS_ASSERT(mem_block->block_size & 0x80000000); #ifdef OS_DEBUG OS_ASSERT(mem_block->mark == STD_MEM_MARK_BEGIN); OS_ASSERT(*(int*)(((OS_BYTE*)(mem_block+1)) + (mem_block->block_size & ~0x80000000)) == STD_MEM_MARK_END); if(mem_block->dbg_id == dbg_breakpoint_id){ DEBUG_BREAK; } if(mem_block == dbg_std_mem_list){ OS_ASSERT(!mem_block->dbg_mem_prev); dbg_std_mem_list = mem_block->dbg_mem_next; }else{ // if(mem_block->dbg_mem_prev){ OS_ASSERT(mem_block->dbg_mem_prev); mem_block->dbg_mem_prev->dbg_mem_next = mem_block->dbg_mem_next; } if(mem_block->dbg_mem_next){ mem_block->dbg_mem_next->dbg_mem_prev = mem_block->dbg_mem_prev; } #endif int size = mem_block->block_size & ~0x80000000; allocated_bytes -= size + sizeof(StdMemBlock) + MEM_MARK_END_SIZE; #ifdef OS_DEBUG OS_MEMSET(ptr, 0xde, size); #endif ::free(mem_block); } void * OS::SmartMemoryManager::malloc(int size OS_DBG_FILEPOS_DECL) { if(size <= 0){ return NULL; } // stat_malloc_count++; #if 0 int start = 0, end = num_page_desc-1; if(size <= page_desc[end].block_size){ for(;;){ if(start >= end){ int block_size = page_desc[start].block_size; if(size > block_size){ start++; } return allocFromPageType(start); } int mid = (start + end) / 2; int block_size = page_desc[mid].block_size; if(size == block_size){ return allocFromPageType(mid); } if(size < block_size){ end = mid - 1; continue; } start = mid + 1; } } #else if(size <= page_desc[num_page_desc-1].block_size){ for(int i = 0; i < num_page_desc; i++){ if(size <= page_desc[i].block_size){ return allocFromPageType(i OS_DBG_FILEPOS_PARAM); } } } #endif return stdAlloc(size OS_DBG_FILEPOS_PARAM); } void OS::SmartMemoryManager::free(void * ptr) { if(!ptr){ return; } // stat_free_count++; #ifdef OS_DEBUG int * p = (int*)ptr - 2; #else int * p = (int*)ptr - 1; #endif int size = p[0]; if(size & 0x80000000){ stdFree(ptr); // p, size & ~0x80000000); return; } MemBlock * mem_block = (MemBlock*)ptr - 1; OS_ASSERT(mem_block->block_size == size); freeMemBlock(mem_block); if(!(stat_free_count % 1024) && cached_bytes > allocated_bytes / 2){ freeCachedMemory(cached_bytes / 2); } } void OS::SmartMemoryManager::setBreakpointId(int id) { #ifdef OS_DEBUG dbg_breakpoint_id = id; #endif } int OS::SmartMemoryManager::getAllocatedBytes() { return allocated_bytes; } int OS::SmartMemoryManager::getMaxAllocatedBytes() { return max_allocated_bytes; } int OS::SmartMemoryManager::getCachedBytes() { return cached_bytes; } // ===================================================================== // ===================================================================== // ===================================================================== OS::OS() { ref_count = 1; memory_manager = NULL; core = NULL; #ifdef OS_DEBUG int mark = 0; native_stack_start_mark = (int)&mark; native_stack_max_usage = 0; #endif } OS::~OS() { OS_ASSERT(ref_count == 0); OS_ASSERT(!core && !memory_manager); // deleteObj(core); // delete memory_manager; // memory_manager->release(); } #ifdef OS_DEBUG void OS::checkNativeStackUsage(const OS_CHAR * func_name) { int mark = 0; int cur_native_stack_usage = (int)&mark - native_stack_start_mark; if(cur_native_stack_usage < 0){ // native_stack_start_mark += cur_native_stack_usage; cur_native_stack_usage = -cur_native_stack_usage; } if(native_stack_max_usage < cur_native_stack_usage){ if(cur_native_stack_usage > 1024*10 && cur_native_stack_usage > native_stack_max_usage * 5 / 4){ printf(OS_TEXT("native stack usage: %.1f Kb (%s)\n"), (float)cur_native_stack_usage/1024.0f, func_name); } native_stack_max_usage = cur_native_stack_usage; } } #endif void * OS::malloc(int size OS_DBG_FILEPOS_DECL) { return memory_manager->malloc(size OS_DBG_FILEPOS_PARAM); } void OS::free(void * p) { memory_manager->free(p); } void * OS::Core::malloc(int size OS_DBG_FILEPOS_DECL) { return allocator->malloc(size OS_DBG_FILEPOS_PARAM); } void OS::Core::free(void * p) { allocator->free(p); } int OS::getAllocatedBytes() { return memory_manager->getAllocatedBytes(); } int OS::getMaxAllocatedBytes() { return memory_manager->getMaxAllocatedBytes(); } int OS::getCachedBytes() { return memory_manager->getCachedBytes(); } void OS::setMemBreakpointId(int id) { memory_manager->setBreakpointId(id); } bool OS::isTerminated() { return core->terminated; } int OS::getTerminatedCode() { return core->terminated_code; } void OS::setTerminated(bool terminated, int code) { core->terminated = terminated; core->terminated_code = code; } void OS::resetTerminated() { core->terminated = false; core->terminated_code = 0; } OS::Core::Core(OS * p_allocator) { allocator = p_allocator; strings = NULL; OS_MEMSET(prototypes, 0, sizeof(prototypes)); // string_values_table = NULL; check_recursion = NULL; // global_vars = NULL; // user_pool = NULL; num_created_values = 0; num_destroyed_values = 0; stack_func = NULL; stack_func_locals = NULL; num_stack_func_locals = 0; stack_func_env_index = 0; stack_func_prog_numbers = NULL; stack_func_prog_strings = NULL; settings.create_compiled_file = true; settings.create_debug_info = true; settings.create_debug_opcodes = true; settings.primary_compiled_file = false; gcInitGreyList(); OS_MEMSET(rand_state, 0, sizeof(rand_state)); rand_next = NULL; rand_seed = 0; rand_left = 0; terminated = false; terminated_code = 0; } OS::Core::~Core() { OS_ASSERT(!strings && global_vars.isNull() && user_pool.isNull() && !check_recursion); for(int i = 0; i < PROTOTYPE_COUNT; i++){ OS_ASSERT(!prototypes[i]); } } OS * OS::create(MemoryManager * manager) { return create(new OS(), manager); } /* OS * OS::create(OS * os, MemoryManager * manager) { return os->start(manager); } */ OS * OS::start(MemoryManager * manager) { if(init(manager)){ return this; } delete this; return NULL; } bool OS::init(MemoryManager * p_manager) { memory_manager = p_manager ? p_manager : new SmartMemoryManager(); core = new (malloc(sizeof(Core) OS_DBG_FILEPOS)) Core(this); if(core->init()){ initPreScript(); initGlobalFunctions(); initObjectClass(); initArrayClass(); initStringClass(); initFunctionClass(); initMathModule(); initGCModule(); initLangTokenizerModule(); initPostScript(); return true; } return false; } void OS::shutdown() { core->shutdown(); core->~Core(); free(core); core = NULL; memory_manager->release(); memory_manager = NULL; } OS * OS::retain() { ref_count++; return this; } void OS::release() { if(--ref_count <= 0){ OS_ASSERT(ref_count == 0); shutdown(); delete this; } } bool OS::Core::init() { // string_values_table = newTable(OS_DBG_FILEPOS_START); for(int i = 0; i < PROTOTYPE_COUNT; i++){ prototypes[i] = newObjectValue(NULL); prototypes[i]->type = OS_VALUE_TYPE_OBJECT; prototypes[i]->external_ref_count++; } check_recursion = newObjectValue(); global_vars = newObjectValue(); user_pool = newObjectValue(); // error_handlers prototypes[PROTOTYPE_BOOL]->prototype = prototypes[PROTOTYPE_OBJECT]; prototypes[PROTOTYPE_NUMBER]->prototype = prototypes[PROTOTYPE_OBJECT]; prototypes[PROTOTYPE_STRING]->prototype = prototypes[PROTOTYPE_OBJECT]; prototypes[PROTOTYPE_ARRAY]->prototype = prototypes[PROTOTYPE_OBJECT]; prototypes[PROTOTYPE_FUNCTION]->prototype = prototypes[PROTOTYPE_OBJECT]; prototypes[PROTOTYPE_USERDATA]->prototype = prototypes[PROTOTYPE_OBJECT]; strings = new (malloc(sizeof(Strings) OS_DBG_FILEPOS)) Strings(allocator); setGlobalValue(OS_TEXT("Object"), Value(prototypes[PROTOTYPE_OBJECT]), false, false); setGlobalValue(OS_TEXT("Boolean"), Value(prototypes[PROTOTYPE_BOOL]), false, false); setGlobalValue(OS_TEXT("Number"), Value(prototypes[PROTOTYPE_NUMBER]), false, false); setGlobalValue(OS_TEXT("String"), Value(prototypes[PROTOTYPE_STRING]), false, false); setGlobalValue(OS_TEXT("Array"), Value(prototypes[PROTOTYPE_ARRAY]), false, false); setGlobalValue(OS_TEXT("Function"), Value(prototypes[PROTOTYPE_FUNCTION]), false, false); setGlobalValue(OS_TEXT("Userdata"), Value(prototypes[PROTOTYPE_USERDATA]), false, false); return true; } int OS::Core::compareGCValues(const void * a, const void * b) { GCValue * v1 = *(GCValue**)a; GCValue * v2 = *(GCValue**)b; if(v1->external_ref_count != v2->external_ref_count){ return v2->external_ref_count - v1->external_ref_count; } return v1->value_id - v2->value_id; } void OS::Core::shutdown() { stack_values.count = 0; while(call_stack_funcs.count > 0){ StackFunction * stack_func = &call_stack_funcs[--call_stack_funcs.count]; clearStackFunction(stack_func); } allocator->vectorClear(call_stack_funcs); // vectorClear(cache_values); // gcFull(); gcResetGreyList(); allocator->deleteObj(strings); int i; // try to finalize the values accurately Vector<GCValue*> collectedValues; allocator->vectorReserveCapacity(collectedValues, values.count OS_DBG_FILEPOS); for(int i = 0; i <= values.head_mask; i++){ for(GCValue * value = values.heads[i]; value; value = value->hash_next){ allocator->vectorAddItem(collectedValues, value OS_DBG_FILEPOS); } } ::qsort(collectedValues.buf, collectedValues.count, sizeof(GCValue*), compareGCValues); for(i = collectedValues.count-1; i >= 0; i--){ deleteValue(collectedValues[i]); } allocator->vectorClear(collectedValues); deleteValues(true); // just clear values.heads check_recursion = NULL; global_vars = (GCValue*)NULL; user_pool = (GCValue*)NULL; for(i = 0; i < OS_ERROR_LEVELS; i++){ error_handlers[i] = NULL; } for(i = 0; i < PROTOTYPE_COUNT; i++){ prototypes[i] = NULL; } deleteStringRefs(); if(stack_values.buf){ // it makes sense because of someone could use stack while the finalizing in process free(stack_values.buf); stack_values.buf = NULL; stack_values.capacity = 0; stack_values.count = 0; } OS_ASSERT(!call_stack_funcs.count); } OS::String OS::changeFilenameExt(const String& filename, const String& ext) { int len = filename.getLen(); for(int i = len-1; i >= 0; i--){ if(filename[i] == OS_TEXT('.')){ return String(this, filename, i, ext, ext.getLen()); } if(OS_IS_SLASH(filename[i])){ break; } } return String(this, filename, len, ext, ext.getLen()); } OS::String OS::changeFilenameExt(const String& filename, const OS_CHAR * ext) { int len = filename.getLen(); for(int i = len-1; i >= 0; i--){ if(filename[i] == OS_TEXT('.')){ if(OS_STRCMP(filename.toChar()+i, ext) == 0){ return filename; } return String(this, filename, i, ext, OS_STRLEN(ext)); } if(OS_IS_SLASH(filename[i])){ break; } } return String(this, filename, len, ext, OS_STRLEN(ext)); } OS::String OS::getFilenameExt(const String& filename) { return getFilenameExt(filename, filename.getLen()); } OS::String OS::getFilenameExt(const OS_CHAR * filename) { return getFilenameExt(filename, OS_STRLEN(filename)); } OS::String OS::getFilenameExt(const OS_CHAR * filename, int len) { for(int i = len-1; i >= 0; i--){ if(filename[i] == OS_TEXT('.')){ return String(this, filename+i, len-i); } if(OS_IS_SLASH(filename[i])){ break; } } return String(this); } OS::String OS::getFilename(const String& filename) { return getFilename(filename, filename.getLen()); } OS::String OS::getFilename(const OS_CHAR * filename) { return getFilename(filename, OS_STRLEN(filename)); } OS::String OS::getFilename(const OS_CHAR * filename, int len) { for(int i = len-1; i >= 0; i--){ if(OS_IS_SLASH(filename[i])){ return String(this, filename+i+1, len-i-1); } } return String(this, filename, len); } OS::String OS::getFilenamePath(const String& filename) { return getFilenamePath(filename, filename.getLen()); } OS::String OS::getFilenamePath(const OS_CHAR * filename) { return getFilenamePath(filename, OS_STRLEN(filename)); } OS::String OS::getFilenamePath(const OS_CHAR * filename, int len) { for(int i = len-1; i >= 0; i--){ if(OS_IS_SLASH(filename[i])){ return String(this, filename, i); } } return String(this); } bool OS::isAbsolutePath(const String& p_filename) { int len = p_filename.getLen(); const OS_CHAR * filename = p_filename; if(OS_IS_ALPHA(filename[0])){ for(int i = 1; i < len-2; i++){ if(!OS_IS_ALPHA(filename[i])){ return filename[i] == OS_TEXT(':') && OS_IS_SLASH(filename[i+1]); } } } return len >= 2 && OS_IS_SLASH(filename[0]) && OS_IS_SLASH(filename[1]); } OS::String OS::resolvePath(const String& filename, const String& cur_path) { String resolved_path = filename; if(!isAbsolutePath(filename) && cur_path.getDataSize()){ resolved_path = cur_path + OS_PATH_SEPARATOR + filename; } resolved_path = changeFilenameExt(filename, OS_SOURCECODE_EXT); if(isFileExist(resolved_path)){ return resolved_path; } resolved_path = changeFilenameExt(filename, OS_COMPILED_EXT); if(isFileExist(resolved_path)){ return resolved_path; } core->error(OS_E_WARNING, String::format(this, OS_TEXT("filename %s is not resolved"), filename.toChar())); return String(this); } OS::String OS::getCompiledFilename(const OS::String& resolved_filename) { return changeFilenameExt(resolved_filename, OS_COMPILED_EXT); } OS::String OS::getDebugInfoFilename(const String& resolved_filename) { return changeFilenameExt(resolved_filename, OS_DEBUG_INFO_EXT); } OS::String OS::getDebugOpcodesFilename(const String& resolved_filename) { if(resolved_filename.getDataSize()){ return changeFilenameExt(resolved_filename, OS_DEBUG_OPCODES_EXT); } static int num_evals = 0; return String(this, Core::String::format(this, OS_TEXT("eval-%d%s"), ++num_evals, OS_DEBUG_OPCODES_EXT)); } OS::String OS::resolvePath(const String& filename) { String cur_path(this); if(core->call_stack_funcs.count > 0){ for(int i = core->call_stack_funcs.count-1; i >= 0; i--){ Core::StackFunction * stack_func = core->call_stack_funcs.buf + i; if(stack_func->func->prog->filename.getLen() > 0){ cur_path = getFilenamePath(stack_func->func->prog->filename); break; } } } return resolvePath(filename, cur_path); } OS::EFileUseType OS::checkFileUsage(const String& sourcecode_filename, const String& compiled_filename) { return COMPILE_SOURCECODE_FILE; } void OS::Core::errorDivisionByZero() { error(OS_E_WARNING, OS_TEXT("division by zero")); } void OS::Core::error(int code, const OS_CHAR * message) { error(code, String(allocator, message)); } void OS::Core::error(int code, const String& message) { Program * prog = NULL; Program::DebugInfoItem * debug_info = NULL; for(int i = call_stack_funcs.count-1; i >= 0 && !debug_info; i--){ Core::StackFunction * stack_func = call_stack_funcs.buf + i; prog = stack_func->func->prog; if(prog->filename.getLen() > 0){ int opcode_pos = stack_func->opcodes.getPos() + stack_func->func->func_decl->opcodes_pos; debug_info = prog->getDebugInfo(opcode_pos); } } int error_level = 0; for(int i = 0; i < OS_ERROR_LEVELS; i++){ if(code & (1<<i)){ error_level = i; break; } } if(error_handlers[error_level].isFunction()){ pushValue(error_handlers[error_level]); pushNull(); pushNumber(code); pushStringValue(message); if(debug_info){ pushStringValue(prog->filename); pushNumber(debug_info->line); call(4, 0); }else{ call(2, 0); } return; } const OS_CHAR * error_type = NULL; switch(code){ case OS_E_WARNING: error_type = OS_TEXT("WARNING"); break; default: case OS_E_ERROR: error_type = OS_TEXT("ERROR"); code = OS_E_ERROR; break; } if(debug_info){ allocator->printf("[%s] %s (line: %d, pos: %d, token: %s, filename: %s)\n", error_type, message.toChar(), debug_info->line, debug_info->pos, debug_info->token.toChar(), prog->filename.toChar()); }else{ allocator->printf("[%s] %s\n", error_type, message.toChar()); } } void OS::Core::gcInitGreyList() { gc_grey_list_first = NULL; gc_grey_root_initialized = false; gc_start_allocated_bytes = 0; gc_max_allocated_bytes = 0; gc_keep_heap_count = 0; gc_continuous_count = 0; gc_continuous = false; gc_values_head_index = -1; gc_time = 0; gc_in_process = false; gc_grey_added_count = 0; // gc_grey_removed_count = 0; gc_start_values_mult = 1.5f; gc_step_size_mult = 0.005f; gc_step_size_auto_mult = 1.0f; gc_start_next_values = 16; gc_step_size = 0; } void OS::Core::gcResetGreyList() { while(gc_grey_list_first){ gcRemoveFromGreyList(gc_grey_list_first); } gc_grey_root_initialized = false; // OS_ASSERT(gc_grey_list.gc_grey_next == (Value*)&gc_grey_list); // OS_ASSERT(gc_grey_list.gc_grey_prev == (Value*)&gc_grey_list); } void OS::Core::gcMarkList(int step_size) { if(step_size < 16){ step_size = 16; } for(; step_size > 0 && gc_grey_list_first; step_size--){ gcMarkValue(gc_grey_list_first); } } void OS::Core::gcMarkTable(Table * table) { Property * prop = table->first, * prop_next; for(; prop; prop = prop_next){ prop_next = prop->next; if(prop->index.type == OS_VALUE_TYPE_WEAKREF){ OS_ASSERT(false); if(!values.get(prop->index.v.value_id)){ PropertyIndex index = *prop; deleteTableProperty(table, index); continue; } } if(prop->value.type == OS_VALUE_TYPE_WEAKREF){ if(!values.get(prop->value.v.value_id)){ PropertyIndex index = *prop; deleteTableProperty(table, index); continue; } } gcAddToGreyList(prop->index); gcAddToGreyList(prop->value); } } void OS::Core::gcMarkProgram(Program * prog) { /* if(prog->gc_time == gc_time){ return; } prog->gc_time = gc_time; */ /* for(int i = 0; i < prog->num_strings; i++){ gcAddToGreyList(prog->const_strings[i]); } */ } void OS::Core::gcMarkUpvalues(Upvalues * upvalues) { if(upvalues->gc_time == gc_time){ return; } upvalues->gc_time = gc_time; int i; for(i = 0; i < upvalues->num_locals; i++){ gcAddToGreyList(upvalues->locals[i]); } for(i = 0; i < upvalues->num_parents; i++){ gcMarkUpvalues(upvalues->getParent(i)); } } void OS::Core::gcMarkStackFunction(StackFunction * stack_func) { OS_ASSERT(stack_func->func && stack_func->func->type == OS_VALUE_TYPE_FUNCTION); gcAddToGreyList(stack_func->func); gcAddToGreyList(stack_func->self); if(stack_func->self_for_proto){ gcAddToGreyList(stack_func->self_for_proto); } gcMarkUpvalues(stack_func->locals); if(stack_func->arguments){ gcAddToGreyList(stack_func->arguments); } if(stack_func->rest_arguments){ gcAddToGreyList(stack_func->rest_arguments); } } void OS::Core::gcAddToGreyList(Value val) { switch(val.type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: gcAddToGreyList(val.v.value); break; } } void OS::Core::gcAddToGreyList(GCValue * value) { if(value->gc_color != GC_WHITE){ return; } // OS_ASSERT(!value->gc_grey_next && !value->gc_grey_prev); OS_ASSERT(!value->gc_grey_next); // gc_grey_list.insertEnd(value); value->gc_grey_next = gc_grey_list_first; gc_grey_list_first = value; value->gc_color = GC_GREY; gc_grey_added_count++; } void OS::Core::gcRemoveFromGreyList(GCValue * value) { // OS_ASSERT(value->gc_grey_next && value->gc_grey_prev); OS_ASSERT(value->gc_color == GC_GREY); OS_ASSERT(gc_grey_list_first == value); // gc_grey_list.remove(value); gc_grey_list_first = value->gc_grey_next; value->gc_grey_next = NULL; value->gc_color = GC_BLACK; // gc_grey_removed_count++; } void OS::Core::gcMarkValue(GCValue * value) { gcRemoveFromGreyList(value); if(value->prototype){ gcAddToGreyList(value->prototype); } if(value->table){ gcMarkTable(value->table); } switch(value->type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: default: OS_ASSERT(false); break; case OS_VALUE_TYPE_STRING: OS_ASSERT(dynamic_cast<GCStringValue*>(value)); break; case OS_VALUE_TYPE_OBJECT: OS_ASSERT(dynamic_cast<GCObjectValue*>(value)); break; case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<GCArrayValue*>(value)); GCArrayValue * arr = (GCArrayValue*)value; for(int i = 0; i < arr->values.count; i++){ gcAddToGreyList(arr->values[i]); } break; } case OS_VALUE_TYPE_FUNCTION: { OS_ASSERT(dynamic_cast<GCFunctionValue*>(value)); GCFunctionValue * func_value = (GCFunctionValue*)value; gcMarkProgram(func_value->prog); gcAddToGreyList(func_value->env); if(func_value->upvalues){ gcMarkUpvalues(func_value->upvalues); } if(func_value->name){ gcAddToGreyList(func_value->name); } break; } case OS_VALUE_TYPE_CFUNCTION: { OS_ASSERT(dynamic_cast<GCCFunctionValue*>(value)); GCCFunctionValue * func_value = (GCCFunctionValue*)value; Value * closure_values = (Value*)(func_value + 1); for(int i = 0; i < func_value->num_closure_values; i++){ gcAddToGreyList(closure_values[i]); } if(func_value->name){ gcAddToGreyList(func_value->name); } break; } case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: OS_ASSERT(dynamic_cast<GCUserdataValue*>(value)); break; } } void OS::onEnterGC() { } void OS::onExitGC() { } int OS::Core::gcStep() { // return OS_GC_PHASE_MARK; if(gc_in_process){ return OS_GC_PHASE_MARK; } struct GCTouch { Core * core; GCTouch(Core * p_core) { core = p_core; core->gc_in_process = true; core->allocator->onEnterGC(); } ~GCTouch() { core->gc_in_process = false; core->allocator->onExitGC(); } } gc_touch(this); if(values.count == 0){ gc_values_head_index = -1; gc_grey_root_initialized = false; gc_continuous = false; return OS_GC_PHASE_MARK; } int step_size = gc_step_size; if(gc_values_head_index >= 0){ OS_ASSERT(gc_values_head_index <= values.head_mask); int i = gc_values_head_index; step_size += 2; // step_size/16; for(; i <= values.head_mask && step_size > 0; i++){ for(GCValue * value = values.heads[i], * next; value; value = next, step_size--){ next = value->hash_next; if(value->gc_color == GC_WHITE && !value->external_ref_count){ OS_ASSERT(!isValueUsed(value)); deleteValue(value); if(gc_values_head_index < 0){ return OS_GC_PHASE_MARK; } }else if(value->gc_color == GC_BLACK){ value->gc_color = GC_WHITE; } } } if(i <= values.head_mask){ gc_values_head_index = i; gc_step_size_auto_mult *= 1.01f; gc_step_size = (int)((float)values.count * gc_step_size_mult * gc_step_size_auto_mult * 2); return OS_GC_PHASE_SWEEP; } gc_values_head_index = -1; gc_start_next_values = (int)((float)values.count * gc_start_values_mult); int end_allocated_bytes = allocator->getAllocatedBytes(); gc_continuous_count++; if(gc_start_allocated_bytes == end_allocated_bytes){ gc_step_size_auto_mult *= 0.5f; if(gc_step_size_auto_mult < 1){ gc_step_size_auto_mult = 1.0f; } if(++gc_keep_heap_count >= 2){ gc_continuous = false; // gc_step_size_auto_mult = 1.0f; } }else{ gc_start_allocated_bytes = end_allocated_bytes; gc_keep_heap_count = 0; } if((!gc_continuous || !(gc_continuous_count%16)) && gc_max_allocated_bytes < end_allocated_bytes){ gc_max_allocated_bytes = end_allocated_bytes; // allocator->printf("[GC] max allocated bytes %d, values %d\n", gc_max_allocated_bytes, values.count); } return OS_GC_PHASE_MARK; } if(!gc_grey_root_initialized){ gc_grey_root_initialized = true; gc_step_size = (int)((float)values.count * gc_step_size_mult * gc_step_size_auto_mult * 2); gc_time++; if(!gc_continuous){ gc_continuous = true; gc_continuous_count = 0; gc_keep_heap_count = 0; // gc_start_allocated_bytes = allocator->getAllocatedBytes(); gc_step_size_auto_mult = 1.0f; }else{ // int i = 0; } // int old_count = gc_grey_added_count; gcAddToGreyList(check_recursion); gcAddToGreyList(global_vars); gcAddToGreyList(user_pool); int i; for(i = 0; i < OS_ERROR_LEVELS; i++){ gcAddToGreyList(error_handlers[i]); } for(i = 0; i < PROTOTYPE_COUNT; i++){ gcAddToGreyList(prototypes[i]); } // gcMarkTable(string_values_table); // step_size -= gc_grey_added_count - old_count; } int i; for(i = 0; i < stack_values.count; i++){ gcAddToGreyList(stack_values[i]); } for(i = 0; i < call_stack_funcs.count; i++){ gcMarkStackFunction(&call_stack_funcs[i]); } gcMarkList(step_size); gc_step_size = (int)((float)values.count * gc_step_size_mult * gc_step_size_auto_mult * 2); if(!gc_grey_list_first){ gc_grey_root_initialized = false; gc_values_head_index = 0; gc_step_size_auto_mult *= 0.25f; if(gc_step_size_auto_mult < 1.0f){ gc_step_size_auto_mult = 1.0f; } return OS_GC_PHASE_SWEEP; } gc_step_size_auto_mult *= 1.01f; return OS_GC_PHASE_MARK; } void OS::Core::gcFinishSweepPhase() { if(gc_in_process || values.count == 0){ return; } if(gc_values_head_index >= 0){ gc_step_size = values.count * 2; gcStep(); OS_ASSERT(gc_values_head_index < 0); } } void OS::Core::gcFinishMarkPhase() { if(gc_in_process || values.count == 0){ return; } while(gc_values_head_index < 0){ gc_step_size = values.count * 2; gcStep(); } } void OS::Core::gcStepIfNeeded() { if(gc_in_process){ return; } if(gc_values_head_index >= 0 || gc_grey_root_initialized || gc_continuous){ gcStep(); }else if(gc_start_next_values <= values.count){ gcFinishSweepPhase(); gcStep(); } } void OS::Core::gcFull() { if(gc_in_process){ return; } gcFinishSweepPhase(); int start_allocated_bytes = allocator->getAllocatedBytes(); for(int i = 1;; i++){ gcFinishMarkPhase(); gcFinishSweepPhase(); int end_allocated_bytes = allocator->getAllocatedBytes(); if(start_allocated_bytes == end_allocated_bytes && i > 1){ return; } start_allocated_bytes = end_allocated_bytes; } } /* void OS::Core::clearValue(Value& val) { switch(val.type){ case OS_VALUE_TYPE_NULL: return; case OS_VALUE_TYPE_BOOL: val.v.boolean = 0; break; case OS_VALUE_TYPE_NUMBER: val.v.number = 0; break; case OS_VALUE_TYPE_WEAKREF: val.v.value_id = 0; break; default: val.v.value = 0; } val.type = OS_VALUE_TYPE_NULL; } */ void OS::Core::clearValue(GCValue * val) { switch(val->type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: default: OS_ASSERT(false); break; case OS_VALUE_TYPE_STRING: { OS_ASSERT(dynamic_cast<GCStringValue*>(val)); break; } case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: { OS_ASSERT(dynamic_cast<GCUserdataValue*>(val)); GCUserdataValue * userdata = (GCUserdataValue*)val; void * ptr = userdata->ptr; OS_UserdataDtor dtor = userdata->dtor; // prevent recursion userdata->ptr = NULL; userdata->crc = 0; userdata->dtor = NULL; if(dtor){ dtor(allocator, ptr, userdata->user_param); } break; } case OS_VALUE_TYPE_FUNCTION: { OS_ASSERT(dynamic_cast<GCFunctionValue*>(val)); GCFunctionValue * func_value = (GCFunctionValue*)val; clearFunctionValue(func_value); break; } case OS_VALUE_TYPE_CFUNCTION: { OS_ASSERT(dynamic_cast<GCCFunctionValue*>(val)); GCCFunctionValue * func_value = (GCCFunctionValue*)val; func_value->func = NULL; func_value->user_param = NULL; func_value->num_closure_values = 0; break; } case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<GCArrayValue*>(val)); GCArrayValue * arr = (GCArrayValue*)val; allocator->vectorClear(arr->values); break; } case OS_VALUE_TYPE_OBJECT: OS_ASSERT(dynamic_cast<GCObjectValue*>(val)); break; } if(val->table){ // when object is destroying, some properties could be already destroyed // so destructor can't use self properties and can break gc process // so destructors are disabled /* { bool prototype_enabled = true; Value * func = getPropertyValue(val, PropertyIndex(strings->__destruct, PropertyIndex::KeepStringIndex()), prototype_enabled); if(func){ pushValue(func); pushValue(val); call(0, 0); } } */ Table * table = val->table; val->table = NULL; deleteTable(table); } if(val->prototype){ // prototype could be already destroyed by gc or will be destroyed soon val->prototype = NULL; } val->type = OS_VALUE_TYPE_UNKNOWN; } #ifdef OS_DEBUG bool OS::Core::isValueUsed(GCValue * val) { struct Lib { Core * core; GCValue * val; bool findAt(Value cur) { GCValue * value = cur.getGCValue(); return value && findAt(value); } bool findAt(Upvalues * upvalues) { int i; for(i = 0; i < upvalues->num_locals; i++){ if(findAt(upvalues->locals[i])){ return true; } } for(i = 0; i < upvalues->num_parents; i++){ if(findAt(upvalues->getParent(i))){ return true; } } return false; } bool findAt(StackFunction * stack_func) { OS_ASSERT(stack_func->func); if(findAt(stack_func->func)){ return true; } if(findAt(stack_func->self)){ return true; } if(stack_func->self_for_proto && findAt(stack_func->self_for_proto)){ return true; } if(stack_func->arguments && findAt(stack_func->arguments)){ return true; } if(stack_func->rest_arguments && findAt(stack_func->rest_arguments)){ return true; } return findAt(stack_func->locals); } bool findAt(Table * table) { OS_ASSERT(table); Property * prop = table->first; for(; prop; prop = prop->next){ if(findAt(prop->index)){ return true; } if(findAt(prop->value)){ return true; } } return false; } bool findAt(GCValue * cur) { OS_ASSERT(cur != (GCValue*)0xdededede); if(cur->gc_time == core->gc_time){ return false; } cur->gc_time = core->gc_time; if(cur == val){ return true; } if(cur->prototype && findAt(cur->prototype)){ return true; } if(cur->table && findAt(cur->table)){ return true; } switch(cur->type){ case OS_VALUE_TYPE_STRING: { OS_ASSERT(dynamic_cast<GCStringValue*>(cur)); GCStringValue * string = (GCStringValue*)cur; OS_ASSERT(!string->table); break; } case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<GCArrayValue*>(cur)); GCArrayValue * arr = (GCArrayValue*)cur; for(int i = 0; i < arr->values.count; i++){ if(findAt(arr->values[i])){ return true; } } break; } case OS_VALUE_TYPE_OBJECT: OS_ASSERT(dynamic_cast<GCObjectValue*>(cur)); break; case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: OS_ASSERT(dynamic_cast<GCUserdataValue*>(cur)); break; case OS_VALUE_TYPE_FUNCTION: { OS_ASSERT(dynamic_cast<GCFunctionValue*>(cur)); GCFunctionValue * func_value = (GCFunctionValue*)cur; if(findAt(func_value->env)){ return true; } if(func_value->upvalues && findAt(func_value->upvalues)){ return true; } if(func_value->name && findAt(func_value->name)){ return true; } for(int i = 0; i < func_value->prog->num_strings; i++){ if(findAt(func_value->prog->const_strings[i])){ return true; } } break; } case OS_VALUE_TYPE_CFUNCTION: { OS_ASSERT(dynamic_cast<GCCFunctionValue*>(cur)); GCCFunctionValue * func_value = (GCCFunctionValue*)cur; Value * closure_values = (Value*)(func_value + 1); for(int i = 0; i < func_value->num_closure_values; i++){ if(findAt(closure_values[i])){ return true; } } if(func_value->name && findAt(func_value->name)){ return true; } break; } case OS_VALUE_TYPE_WEAKREF: break; default: OS_ASSERT(false); } return false; } } lib = {this, val}; if(lib.findAt(check_recursion)){ return true; } if(lib.findAt(global_vars)){ return true; } if(lib.findAt(user_pool)){ return true; } int i; for(i = 0; i < PROTOTYPE_COUNT; i++){ if(lib.findAt(prototypes[i])){ return true; } } for(i = 0; i < stack_values.count; i++){ if(lib.findAt(stack_values[i])){ return true; } } for(i = 0; i < call_stack_funcs.count; i++){ if(lib.findAt(&call_stack_funcs[i])){ return true; } } return false; } #endif void OS::Core::deleteValue(GCValue * val) { OS_ASSERT(val); OS_ASSERT(val->gc_color != GC_GREY); unregisterValue(val->value_id); clearValue(val); val->~GCValue(); free(val); num_destroyed_values++; } OS::Core::Property * OS::Core::setTableValue(Table * table, const PropertyIndex& index, Value value) { OS_ASSERT(table); // TODO: correct ??? gcAddToGreyList(value); Property * prop = table->get(index); if(prop){ prop->value = value; return prop; } prop = new (malloc(sizeof(Property) OS_DBG_FILEPOS)) Property(index); prop->value = value; addTableProperty(table, prop); return prop; } bool OS::Core::hasSpecialPrefix(const Value& value) { if(value.type != OS_VALUE_TYPE_STRING){ return false; } OS_ASSERT(dynamic_cast<GCStringValue*>(value.v.string)); GCStringValue * string = value.v.string; if(string->getLen() >= 2){ const OS_CHAR * s = string->toChar(); return s[0] == OS_TEXT('_') && s[1] == OS_TEXT('_'); } return false; } void OS::Core::setPropertyValue(GCValue * table_value, const PropertyIndex& index, Value value, bool anonymous_setter_enabled, bool named_setter_enabled) { #if defined OS_DEBUG && defined OS_WARN_NULL_INDEX if(table_value != check_recursion && index.index.type == OS_VALUE_TYPE_NULL){ error(OS_E_WARNING, OS_TEXT("object set null index")); } #endif // TODO: correct ??? gcAddToGreyList(value); if(index.index.type == OS_VALUE_TYPE_STRING){ OS_ASSERT(dynamic_cast<GCStringValue*>(index.index.v.string)); switch(value.type){ case OS_VALUE_TYPE_FUNCTION: OS_ASSERT(dynamic_cast<GCFunctionValue*>(value.v.func)); if(!value.v.func->name){ value.v.func->name = index.index.v.string; } break; case OS_VALUE_TYPE_CFUNCTION: OS_ASSERT(dynamic_cast<GCCFunctionValue*>(value.v.cfunc)); if(!value.v.cfunc->name){ value.v.cfunc->name = index.index.v.string; } break; } } Property * prop = NULL; Table * table = table_value->table; if(table && (prop = table->get(index))){ prop->value = value; return; } // prototype should not be used in set /* if(prototype_enabled){ GCValue * cur_value = table_value; while(cur_value->prototype){ cur_value = cur_value->prototype; Table * cur_table = cur_value->table; if(cur_table && (prop = cur_table->get(index))){ prop->value = value; return; } } } */ if(index.index.type == OS_VALUE_TYPE_STRING && strings->syntax_prototype == index.index.v.string){ switch(table_value->type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: table_value->prototype = value.v.value; break; case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_CFUNCTION: // TODO: warning??? break; } return; } if(table_value->type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<GCArrayValue*>(table_value)); GCArrayValue * arr = (GCArrayValue*)table_value; int i = (int)valueToInt(index.index); if(i >= 0){ while(i >= arr->values.count){ allocator->vectorAddItem(arr->values, Value() OS_DBG_FILEPOS); } OS_ASSERT(i < arr->values.count); arr->values[i] = value; } return; } if((anonymous_setter_enabled || named_setter_enabled) && !hasSpecialPrefix(index.index)){ Value func; if(index.index.type == OS_VALUE_TYPE_STRING && named_setter_enabled){ const void * buf1 = strings->__setAt.toChar(); int size1 = strings->__setAt.getDataSize(); const void * buf2 = index.index.v.string->toChar(); int size2 = index.index.v.string->getDataSize(); GCStringValue * setter_name = newStringValue(buf1, size1, buf2, size2); if(getPropertyValue(func, table_value, PropertyIndex(setter_name, PropertyIndex::KeepStringIndex()), true)){ pushValue(func); pushValue(table_value); pushValue(value); call(1, 0); return; } } if(anonymous_setter_enabled && getPropertyValue(func, table_value, PropertyIndex(strings->__set, PropertyIndex::KeepStringIndex()), true)){ pushValue(func); pushValue(table_value); pushValue(index.index); pushValue(value); call(2, 0); return; } } if(table_value->type == OS_VALUE_TYPE_STRING){ // TODO: trigger error??? return; } if(!table){ table_value->table = table = newTable(OS_DBG_FILEPOS_START); } prop = new (malloc(sizeof(Property) OS_DBG_FILEPOS)) Property(index); prop->value = value; addTableProperty(table, prop); // setTableValue(table, index, value); } void OS::Core::setPropertyValue(Value table_value, const PropertyIndex& index, Value value, bool anonymous_setter_enabled, bool named_setter_enabled) { switch(table_value.type){ case OS_VALUE_TYPE_NULL: return; case OS_VALUE_TYPE_BOOL: // return setPropertyValue(prototypes[PROTOTYPE_BOOL], index, value, setter_enabled); return; case OS_VALUE_TYPE_NUMBER: // return setPropertyValue(prototypes[PROTOTYPE_NUMBER], index, value, setter_enabled); return; case OS_VALUE_TYPE_STRING: // return setPropertyValue(prototypes[PROTOTYPE_STRING], index, value, setter_enabled); // return; case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return setPropertyValue(table_value.v.value, index, value, anonymous_setter_enabled, named_setter_enabled); } } void OS::Core::pushPrototype(Value val) { switch(val.type){ case OS_VALUE_TYPE_NULL: pushNull(); return; case OS_VALUE_TYPE_BOOL: pushValue(prototypes[PROTOTYPE_BOOL]); return; case OS_VALUE_TYPE_NUMBER: pushValue(prototypes[PROTOTYPE_NUMBER]); return; case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: pushValue(val.v.value); return; } } void OS::Core::setPrototype(Value val, Value proto, int userdata_crc) { switch(val.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: return; case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: if(val.v.userdata->crc != userdata_crc){ return; } // no break case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: val.v.value->prototype = proto.getGCValue(); return; } } OS::Core::GCStringValue * OS::Core::newStringValue(const OS_CHAR * str) { return newStringValue(str, OS_STRLEN(str)); } OS::Core::GCStringValue * OS::Core::newStringValue(const OS_CHAR * str, int len) { return newStringValue((void*)str, len * sizeof(OS_CHAR)); } OS::Core::GCStringValue * OS::Core::newStringValue(const OS_CHAR * str, int len, const OS_CHAR * str2, int len2) { return newStringValue((void*)str, len * sizeof(OS_CHAR), str2, len2 * sizeof(OS_CHAR)); } OS::Core::GCStringValue * OS::Core::newStringValue(const OS_CHAR * str, int len, bool trim_left, bool trim_right) { if(trim_left){ while(len > 0 && OS_IS_SPACE(*str)){ str++; len--; } } if(trim_right){ while(len > 0 && OS_IS_SPACE(str[len-1])){ len--; } } return newStringValue((void*)str, len * sizeof(OS_CHAR)); } OS::Core::GCStringValue * OS::Core::newStringValue(const String& p_str, bool trim_left, bool trim_right) { const OS_CHAR * str = p_str.toChar(); int len = p_str.getLen(); bool changed = false; if(trim_left){ while(len > 0 && OS_IS_SPACE(*str)){ str++; len--; changed = true; } } if(trim_right){ while(len > 0 && OS_IS_SPACE(str[len-1])){ len--; changed = true; } } if(changed){ return newStringValue(str, len); } return p_str.string; } OS::Core::GCStringValue * OS::Core::newStringValue(const String& str) { return str.string; } OS::Core::GCStringValue * OS::Core::newStringValue(const void * buf, int size) { return newStringValue(buf, size, NULL, 0); } OS::Core::GCStringValue * OS::Core::newStringValue(const void * buf1, int size1, const void * buf2, int size2) { if(string_refs.count > 0){ OS_ASSERT(string_refs.heads && string_refs.head_mask); int hash = Utils::keyToHash(buf1, size1, buf2, size2); int slot = hash & string_refs.head_mask; StringRef * str_ref = string_refs.heads[slot]; for(StringRef * prev = NULL, * next; str_ref; str_ref = next){ next = str_ref->hash_next; GCStringValue * string_value = (GCStringValue*)values.get(str_ref->string_value_id); if(!string_value){ if(!prev){ string_refs.heads[slot] = next; }else{ prev->hash_next = next; } free(str_ref); string_refs.count--; continue; } OS_ASSERT(string_value->type == OS_VALUE_TYPE_STRING); OS_ASSERT(dynamic_cast<GCStringValue*>(string_value)); if(string_value->isEqual(hash, buf1, size1, buf2, size2)){ return string_value; } prev = str_ref; } } GCStringValue * string_value = GCStringValue::alloc(allocator, buf1, size1, buf2, size2 OS_DBG_FILEPOS); StringRef * str_ref = (StringRef*)malloc(sizeof(StringRef) OS_DBG_FILEPOS); str_ref->string_hash = string_value->hash; str_ref->string_value_id = string_value->value_id; str_ref->hash_next = NULL; registerStringRef(str_ref); return string_value; } OS::Core::GCStringValue * OS::Core::newStringValue(const void * buf1, int size1, const void * buf2, int size2, const void * buf3, int size3) { if(size1 <= 0){ return newStringValue(buf2, size2, buf3, size3); } if(size2 <= 0){ return newStringValue(buf1, size1, buf3, size3); } if(size3 <= 0){ return newStringValue(buf1, size1, buf2, size2); } if(size1 + size2 + size3 <= 1024){ OS_BYTE * buf = (OS_BYTE*)alloca(size1 + size2 + size3 + sizeof(OS_CHAR)); OS_MEMCPY(buf, buf1, size1); OS_MEMCPY(buf+size1, buf2, size2); OS_MEMCPY(buf+size1+size2, buf3, size3); buf[size1+size2+size3] = (OS_CHAR)0; return newStringValue(buf, (size1 + size2 + size3) / sizeof(OS_CHAR)); } GCStringValue * str = newStringValue(buf1, size1, buf2, size2); return newStringValue(str->toBytes(), str->data_size, buf3, size3); } OS::Core::GCStringValue * OS::Core::newStringValue(GCStringValue * a, GCStringValue * b) { if(a->data_size <= 0){ return b; } if(b->data_size <= 0){ return a; } return newStringValue((void*)a->toBytes(), a->data_size, (void*)b->toBytes(), b->data_size); } OS::Core::GCStringValue * OS::Core::newStringValue(const String& a, const String& b) { return newStringValue(a.string, b.string); } OS::Core::GCStringValue * OS::Core::newStringValue(OS_INT val) { OS_CHAR str[128]; Utils::numToStr(str, val); return newStringValue(str); } OS::Core::GCStringValue * OS::Core::newStringValue(OS_FLOAT val, int precision) { OS_CHAR str[128]; Utils::numToStr(str, val, precision); return newStringValue(str); } OS::Core::GCStringValue * OS::Core::newStringValue(int temp_buf_len, const OS_CHAR * fmt, ...) { va_list va; va_start(va, fmt); OS_VaListDtor va_dtor(&va); return newStringValueVa(temp_buf_len, fmt, va); } OS::Core::GCStringValue * OS::Core::newStringValueVa(int temp_buf_len, const OS_CHAR * fmt, va_list va) { OS_ASSERT(temp_buf_len <= OS_DEF_FMT_BUF_LEN); OS_CHAR * buf = (OS_CHAR*)malloc(temp_buf_len * sizeof(OS_CHAR) OS_DBG_FILEPOS); OS_VSNPRINTF(buf, sizeof(OS_CHAR) * (temp_buf_len-1), fmt, va); GCStringValue * result = newStringValue(buf); free(buf); return result; } OS::Core::GCCFunctionValue * OS::Core::newCFunctionValue(OS_CFunction func, void * user_param) { return newCFunctionValue(func, 0, user_param); } OS::Core::GCCFunctionValue * OS::Core::newCFunctionValue(OS_CFunction func, int num_closure_values, void * user_param) { OS_ASSERT(stack_values.count >= num_closure_values); if(!func){ return NULL; } GCCFunctionValue * res = new (malloc(sizeof(GCCFunctionValue) + sizeof(Value) * num_closure_values OS_DBG_FILEPOS)) GCCFunctionValue(); res->prototype = prototypes[PROTOTYPE_FUNCTION]; res->name = NULL; res->func = func; res->user_param = user_param; res->num_closure_values = num_closure_values; Value * closure_values = (Value*)(res + 1); if(num_closure_values > 0){ OS_MEMCPY(closure_values, stack_values.buf + (stack_values.count - num_closure_values), sizeof(Value)*num_closure_values); } res->type = OS_VALUE_TYPE_CFUNCTION; pop(num_closure_values); registerValue(res); return res; } OS::Core::GCUserdataValue * OS::Core::newUserdataValue(int crc, int data_size, OS_UserdataDtor dtor, void * user_param) { GCUserdataValue * res = new (malloc(sizeof(GCUserdataValue) + data_size OS_DBG_FILEPOS)) GCUserdataValue(); res->prototype = prototypes[PROTOTYPE_USERDATA]; res->crc = crc; res->dtor = dtor; res->user_param = user_param; res->ptr = data_size ? res + 1 : NULL; res->type = OS_VALUE_TYPE_USERDATA; registerValue(res); return res; } OS::Core::GCUserdataValue * OS::Core::newUserPointerValue(int crc, void * data, OS_UserdataDtor dtor, void * user_param) { GCUserdataValue * res = new (malloc(sizeof(GCUserdataValue) OS_DBG_FILEPOS)) GCUserdataValue(); res->prototype = prototypes[PROTOTYPE_USERDATA]; res->crc = crc; res->dtor = dtor; res->user_param = user_param; res->ptr = data; res->type = OS_VALUE_TYPE_USERDATA; // PTR; registerValue(res); return res; } OS::Core::GCObjectValue * OS::Core::newObjectValue() { return newObjectValue(prototypes[PROTOTYPE_OBJECT]); } OS::Core::GCObjectValue * OS::Core::newObjectValue(GCValue * prototype) { GCObjectValue * res = new (malloc(sizeof(GCObjectValue) OS_DBG_FILEPOS)) GCObjectValue(); res->prototype = prototype; res->type = OS_VALUE_TYPE_OBJECT; registerValue(res); return res; } OS::Core::GCArrayValue * OS::Core::newArrayValue(int initial_capacity) { GCArrayValue * res = new (malloc(sizeof(GCArrayValue) OS_DBG_FILEPOS)) GCArrayValue(); res->prototype = prototypes[PROTOTYPE_ARRAY]; res->type = OS_VALUE_TYPE_ARRAY; if(initial_capacity > 0){ allocator->vectorReserveCapacity(res->values, initial_capacity OS_DBG_FILEPOS); } registerValue(res); return res; } void OS::Core::pushValue(const Value& p_val) { StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ Value val = p_val; reserveStackValues(stack_values.count+1); stack_values.buf[stack_values.count++] = val; }else{ stack_values.buf[stack_values.count++] = p_val; } } void OS::Core::pushNull() { pushValue(Value()); } void OS::Core::pushStackValue(int offs) { pushValue(getStackValue(offs)); } void OS::Core::copyValue(int raw_from, int raw_to) { reserveStackValues(raw_to+1); stack_values.buf[raw_to] = stack_values.buf[raw_from]; } /* void OS::Core::pushTrue() { pushValue(true); } void OS::Core::pushFalse() { pushValue(false); } */ void OS::Core::pushBool(bool val) { #if 1 StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ reserveStackValues(stack_values.count+1); } stack_values.buf[stack_values.count++] = val; #else pushValue(val); #endif } void OS::Core::pushNumber(OS_INT32 val) { #if 1 StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ reserveStackValues(stack_values.count+1); } stack_values.buf[stack_values.count++] = val; #else pushValue(val); #endif } void OS::Core::pushNumber(OS_INT64 val) { #if 1 StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ reserveStackValues(stack_values.count+1); } stack_values.buf[stack_values.count++] = val; #else pushValue(val); #endif } void OS::Core::pushNumber(float val) { #if 1 StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ reserveStackValues(stack_values.count+1); } stack_values.buf[stack_values.count++] = val; #else pushValue(val); #endif } void OS::Core::pushNumber(double val) { #if 1 StackValues& stack_values = this->stack_values; if(stack_values.capacity < stack_values.count+1){ reserveStackValues(stack_values.count+1); } stack_values.buf[stack_values.count++] = val; #else pushValue(val); #endif } OS::Core::GCStringValue * OS::Core::pushStringValue(const String& val) { return pushValue(newStringValue(val)); } OS::Core::GCStringValue * OS::Core::pushStringValue(const OS_CHAR * val) { return pushValue(newStringValue(val)); } OS::Core::GCStringValue * OS::Core::pushStringValue(const OS_CHAR * val, int len) { return pushValue(newStringValue(val, len)); } OS::Core::GCCFunctionValue * OS::Core::pushCFunctionValue(OS_CFunction func, void * user_param) { return pushValue(newCFunctionValue(func, user_param)); } OS::Core::GCCFunctionValue * OS::Core::pushCFunctionValue(OS_CFunction func, int closure_values, void * user_param) { return pushValue(newCFunctionValue(func, closure_values, user_param)); } OS::Core::GCUserdataValue * OS::Core::pushUserdataValue(int crc, int data_size, OS_UserdataDtor dtor, void * user_param) { return pushValue(newUserdataValue(crc, data_size, dtor, user_param)); } OS::Core::GCUserdataValue * OS::Core::pushUserPointerValue(int crc, void * data, OS_UserdataDtor dtor, void * user_param) { return pushValue(newUserPointerValue(crc, data, dtor, user_param)); } OS::Core::GCObjectValue * OS::Core::pushObjectValue() { return pushValue(newObjectValue()); } OS::Core::GCObjectValue * OS::Core::pushObjectValue(GCValue * prototype) { return pushValue(newObjectValue(prototype)); } OS::Core::GCArrayValue * OS::Core::pushArrayValue(int initial_capacity) { return pushValue(newArrayValue(initial_capacity)); } void OS::Core::pushTypeOf(Value val) { switch(val.type){ // case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_BOOL: pushStringValue(strings->typeof_boolean); return; case OS_VALUE_TYPE_NUMBER: pushStringValue(strings->typeof_number); return; case OS_VALUE_TYPE_STRING: pushStringValue(strings->typeof_string); return; case OS_VALUE_TYPE_ARRAY: pushStringValue(strings->typeof_array); return; case OS_VALUE_TYPE_OBJECT: pushStringValue(strings->typeof_object); return; case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: pushStringValue(strings->typeof_userdata); return; case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: pushStringValue(strings->typeof_function); return; } pushStringValue(strings->typeof_null); } bool OS::Core::pushNumberOf(Value val) { if(val.type == OS_VALUE_TYPE_NUMBER){ pushValue(val); return true; } OS_NUMBER number; if(isValueNumber(val, &number)){ pushNumber(number); return true; } pushNull(); return false; } bool OS::Core::pushStringOf(Value val) { if(val.type == OS_VALUE_TYPE_STRING){ pushValue(val); return true; } String str(allocator); if(isValueString(val, &str)){ pushStringValue(str); return true; } pushNull(); return false; } bool OS::Core::pushValueOf(Value val) { switch(val.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: pushValue(val); return true; } OS_ASSERT(check_recursion && check_recursion->type == OS_VALUE_TYPE_OBJECT); if(++check_recursion->external_ref_count == 1 && check_recursion->table){ clearTable(check_recursion->table); } setPropertyValue(check_recursion, val, Value(true), false, false); struct Finalizer { Core * core; ~Finalizer() { if(--core->check_recursion->external_ref_count == 0 && core->check_recursion->table){ core->clearTable(core->check_recursion->table); } if(core->check_recursion->gc_color == GC_WHITE){ core->check_recursion->gc_color = GC_BLACK; } } } finalizer = {this}; bool prototype_enabled = true; Value func; if(getPropertyValue(func, val.v.value, PropertyIndex(strings->__valueof, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { pushValue(func); pushValue(val); call(0, 1); switch(stack_values.lastElement().type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: return true; } // TODO: warning pop(); } pushNull(); return false; } OS::Core::GCArrayValue * OS::Core::pushArrayOf(Value val) { // GCArrayValue * arr; switch(val.type){ // case OS_VALUE_TYPE_NULL: // return pushNull(); // pushArrayValue(); /* case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_STRING: arr = pushArrayValue(); allocator->vectorAddItem(arr->values, val OS_DBG_FILEPOS); return arr; */ case OS_VALUE_TYPE_ARRAY: return pushValue(val.v.arr); /* case OS_VALUE_TYPE_OBJECT: arr = pushArrayValue(); if(val.v.object->table && val.v.object->table->count > 0){ Property * prop = val.v.object->table->first; for(; prop; prop = prop->next){ allocator->vectorAddItem(arr->values, prop->value OS_DBG_FILEPOS); } } return arr; */ } pushNull(); return NULL; } OS::Core::GCObjectValue * OS::Core::pushObjectOf(Value val) { // GCObjectValue * object; switch(val.type){ // case OS_VALUE_TYPE_NULL: // return pushObjectValue(); /* case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_STRING: object = pushObjectValue(); setPropertyValue(object, Value(0), val, false); return object; case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<GCArrayValue*>(val.v.arr)); object = pushObjectValue(); GCArrayValue * arr = (GCArrayValue*)val.v.arr; for(int i = 0; i < arr->values.count; i++){ setPropertyValue(object, Value(i), arr->values[i], false); } return object; } */ case OS_VALUE_TYPE_OBJECT: return pushValue(val.v.object); } pushNull(); return NULL; } OS::Core::GCUserdataValue * OS::Core::pushUserdataOf(Value val) { switch(val.type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return pushValue(val.v.userdata); } pushNull(); return NULL; } bool OS::Core::pushFunctionOf(Value val) { switch(val.type){ case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: pushValue(val); return true; } pushNull(); return false; } void OS::Core::pushCloneValue(Value val) { GCValue * value, * new_value; switch(val.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_STRING: pushValue(val); return; case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<GCArrayValue*>(val.v.value)); value = val.v.value; new_value = pushArrayValue(); new_value->prototype = value->prototype; GCArrayValue * arr = (GCArrayValue*)value; GCArrayValue * new_arr = (GCArrayValue*)new_value; allocator->vectorReserveCapacity(new_arr->values, arr->values.count OS_DBG_FILEPOS); for(int i = 0; i < arr->values.count; i++){ allocator->vectorAddItem(new_arr->values, arr->values[i] OS_DBG_FILEPOS); } break; } case OS_VALUE_TYPE_OBJECT: value = val.v.value; new_value = pushObjectValue(value->prototype); break; case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_CFUNCTION: value = val.v.value; new_value = pushValue(value); break; default: pushNull(); return; } OS_ASSERT(new_value->type != OS_VALUE_TYPE_NULL); if(new_value != value && value->table && value->table->count > 0){ #if 1 new_value->table = newTable(OS_DBG_FILEPOS_START); copyTableProperties(new_value->table, value->table); #else copyTableProperties(new_value, value, true); #endif } // removeStackValue(-2); switch(new_value->type){ case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: { bool prototype_enabled = true; Value func; if(getPropertyValue(func, new_value, PropertyIndex(strings->__clone, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { pushValue(func); pushValue(new_value); call(0, 1); OS_ASSERT(stack_values.count >= 2); removeStackValue(-2); } } } } void OS::Core::pushOpResultValue(int opcode, Value value) { struct Lib { Core * core; void pushSimpleOpcodeValue(int opcode, Value value) { switch(opcode){ case Program::OP_BIT_NOT: return core->pushNumber(~core->valueToInt(value)); case Program::OP_PLUS: if(value.type == OS_VALUE_TYPE_NUMBER){ return core->pushValue(value); } return core->pushNumber(core->valueToNumber(value)); case Program::OP_NEG: return core->pushNumber(-core->valueToNumber(value)); case Program::OP_LENGTH: // return core->pushNumber(core->valueToString(value).getDataSize() / sizeof(OS_CHAR)); return pushObjectMethodOpcodeValue(core->strings->__len, value); } return core->pushNull(); } void pushObjectMethodOpcodeValue(const String& method_name, Value value) { bool prototype_enabled = true; Value func; if(core->getPropertyValue(func, value, PropertyIndex(method_name, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { core->pushValue(func); core->pushValue(value); core->call(0, 1); return; } return core->pushNull(); } void pushObjectOpcodeValue(int opcode, Value value) { switch(opcode){ case Program::OP_BIT_NOT: return pushObjectMethodOpcodeValue(core->strings->__bitnot, value); case Program::OP_PLUS: return pushObjectMethodOpcodeValue(core->strings->__plus, value); case Program::OP_NEG: return pushObjectMethodOpcodeValue(core->strings->__neg, value); case Program::OP_LENGTH: return pushObjectMethodOpcodeValue(core->strings->__len, value); } return core->pushNull(); } void pushUnaryOpcodeValue(int opcode, Value value) { switch(value.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: return pushSimpleOpcodeValue(opcode, value); case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return pushObjectOpcodeValue(opcode, value); } return core->pushNull(); } } lib = {this}; return lib.pushUnaryOpcodeValue(opcode, value); } void OS::Core::pushOpResultValue(int opcode, Value left_value, Value right_value) { struct Lib { Core * core; bool isEqualExactly(Value left_value, Value right_value) { if(left_value.type == right_value.type){ // && left_value->prototype == right_value->prototype){ switch(left_value.type){ case OS_VALUE_TYPE_NULL: return true; case OS_VALUE_TYPE_NUMBER: return left_value.v.number == right_value.v.number; case OS_VALUE_TYPE_BOOL: return left_value.v.boolean == right_value.v.boolean; case OS_VALUE_TYPE_STRING: // the same strings are always share one instance, so check only value_id case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return left_value.v.value == right_value.v.value; case OS_VALUE_TYPE_WEAKREF: return left_value.v.value_id == right_value.v.value_id; } } return false; } int compareNumbers(OS_NUMBER num1, OS_NUMBER num2) { if(num1 > num2){ return 1; } if(num1 < num2){ return -1; } return 0; } int compareStrings(GCStringValue * left_string_data, OS_NUMBER right_number) { OS_CHAR buf[128]; Utils::numToStr(buf, right_number); return left_string_data->cmp(buf); } int compareStrings(GCStringValue * left_string_data, GCStringValue * right_string_data) { return left_string_data->cmp(right_string_data); } int compareObjectToValue(Value left_value, Value right_value) { GCValue * left = left_value.v.value; switch(left->type){ case OS_VALUE_TYPE_STRING: { OS_ASSERT(dynamic_cast<GCStringValue*>(left)); GCStringValue * string = (GCStringValue*)left; return compareStringToValue(left_value, string, right_value); } case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: switch(right_value.type){ case OS_VALUE_TYPE_NULL: return 1; case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: { bool prototype_enabled = true; Value func; if(core->getPropertyValue(func, left, PropertyIndex(core->strings->__cmp, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { core->pushValue(func); core->pushValue(left); core->pushValue(right_value); core->call(1, 1); OS_ASSERT(core->stack_values.count >= 1); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {core}; Value value = core->stack_values.lastElement(); if(value.type == OS_VALUE_TYPE_NUMBER){ return (int)value.v.number; } } if(right_value.type != OS_VALUE_TYPE_STRING && right_value.type != OS_VALUE_TYPE_NUMBER && right_value.type != OS_VALUE_TYPE_BOOL){ GCValue * right = right_value.v.value; OS_ASSERT(right->type == right_value.type); if(left->prototype != right->prototype){ switch(right->type){ case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: if(core->getPropertyValue(func, right, PropertyIndex(core->strings->__cmp, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { core->pushValue(func); core->pushValue(right_value); core->pushValue(left); core->call(1, 1); OS_ASSERT(core->stack_values.count >= 1); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {core}; Value value = core->stack_values.lastElement(); if(value.type == OS_VALUE_TYPE_NUMBER){ return -(int)value.v.number; } } } } } core->pushValueOf(Value(left)); Value left_value = core->stack_values.lastElement(); struct Pop { Core * core; ~Pop(){ core->pop(); } } pop = {core}; return compareValues(left_value, right_value); } } break; } // generic compare return 1; // left->value_id - (int)right_value; } int compareNumberToValue(Value left_value, OS_NUMBER left_number, Value right_value) { switch(right_value.type){ case OS_VALUE_TYPE_NULL: return 1; case OS_VALUE_TYPE_NUMBER: return compareNumbers(left_number, right_value.v.number); case OS_VALUE_TYPE_BOOL: return compareNumbers(left_number, (OS_NUMBER)right_value.v.boolean); case OS_VALUE_TYPE_STRING: return -compareStrings(right_value.v.string, left_number); } return -compareObjectToValue(right_value, left_value); } int compareStringToValue(Value left_value, GCStringValue * left_string_data, Value right_value) { switch(right_value.type){ case OS_VALUE_TYPE_NULL: return 1; case OS_VALUE_TYPE_NUMBER: return compareStrings(left_string_data, right_value.v.number); case OS_VALUE_TYPE_BOOL: return compareStrings(left_string_data, (OS_NUMBER)right_value.v.boolean); case OS_VALUE_TYPE_STRING: return compareStrings(left_string_data, right_value.v.string); } return -compareObjectToValue(right_value, left_value); } int compareValues(Value left_value, Value right_value) { switch(left_value.type){ case OS_VALUE_TYPE_NULL: return right_value.type == OS_VALUE_TYPE_NULL ? 0 : -1; case OS_VALUE_TYPE_NUMBER: return compareNumberToValue(left_value, left_value.v.number, right_value); case OS_VALUE_TYPE_BOOL: return compareNumberToValue(left_value, (OS_NUMBER)left_value.v.boolean, right_value); // case OS_VALUE_TYPE_STRING: // return compareStringToValue(left_value->v.string_data, right_value); } return compareObjectToValue(left_value, right_value); } void pushSimpleOpcodeValue(int opcode, Value left_value, Value right_value) { switch(opcode){ case Program::OP_CONCAT: core->pushStringValue(core->newStringValue(core->valueToString(left_value), core->valueToString(right_value))); return; case Program::OP_BIT_AND: return core->pushNumber(core->valueToInt(left_value) & core->valueToInt(right_value)); case Program::OP_BIT_OR: return core->pushNumber(core->valueToInt(left_value) | core->valueToInt(right_value)); case Program::OP_BIT_XOR: return core->pushNumber(core->valueToInt(left_value) ^ core->valueToInt(right_value)); case Program::OP_ADD: // + return core->pushNumber(core->valueToNumber(left_value) + core->valueToNumber(right_value)); case Program::OP_SUB: // - return core->pushNumber(core->valueToNumber(left_value) - core->valueToNumber(right_value)); case Program::OP_MUL: // * return core->pushNumber(core->valueToNumber(left_value) * core->valueToNumber(right_value)); case Program::OP_DIV: // / { OS_FLOAT right = core->valueToNumber(right_value); if(!right){ core->errorDivisionByZero(); return core->pushNumber(0.0); } return core->pushNumber(core->valueToNumber(left_value) / right); } case Program::OP_MOD: // % { OS_FLOAT right = core->valueToNumber(right_value); if(!right){ core->errorDivisionByZero(); return core->pushNumber(0.0); } return core->pushNumber(OS_MATH_MOD_OPERATOR(core->valueToNumber(left_value), right)); } case Program::OP_LSHIFT: // << return core->pushNumber(core->valueToInt(left_value) << core->valueToInt(right_value)); case Program::OP_RSHIFT: // >> return core->pushNumber(core->valueToInt(left_value) >> core->valueToInt(right_value)); case Program::OP_POW: // ** return core->pushNumber(OS_MATH_POW_OPERATOR(core->valueToNumber(left_value), core->valueToNumber(right_value))); } core->pushNull(); } void pushObjectMethodOpcodeValue(int opcode, const String& method_name, Value left_value, Value right_value, GCValue * object, bool is_left_side) { bool prototype_enabled = true; Value func; if(core->getPropertyValue(func, object, PropertyIndex(method_name, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { core->pushValue(func); core->pushValue(object); core->pushValue(left_value); core->pushValue(right_value); core->pushValue(is_left_side ? right_value : left_value); core->call(3, 1); return; } Value other_value = is_left_side ? right_value : left_value; switch(other_value.type){ case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: { GCValue * other = other_value.v.value; if(object->prototype == other->prototype){ core->pushNull(); return; } if(core->getPropertyValue(func, other, PropertyIndex(method_name, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { core->pushValue(func); core->pushValue(other_value); core->pushValue(left_value); core->pushValue(right_value); core->pushValue(!is_left_side ? right_value : left_value); core->call(3, 1); return; } } } if(is_left_side){ core->pushValueOf(left_value); pushBinaryOpcodeValue(opcode, core->stack_values.lastElement(), right_value); core->removeStackValue(-2); }else{ core->pushValueOf(right_value); pushBinaryOpcodeValue(opcode, left_value, core->stack_values.lastElement()); core->removeStackValue(-2); } } void pushObjectOpcodeValue(int opcode, Value left_value, Value right_value, GCValue * object, bool is_left_side) { switch(opcode){ case Program::OP_CONCAT: return pushObjectMethodOpcodeValue(opcode, core->strings->__concat, left_value, right_value, object, is_left_side); case Program::OP_BIT_AND: return pushObjectMethodOpcodeValue(opcode, core->strings->__bitand, left_value, right_value, object, is_left_side); case Program::OP_BIT_OR: return pushObjectMethodOpcodeValue(opcode, core->strings->__bitor, left_value, right_value, object, is_left_side); case Program::OP_BIT_XOR: return pushObjectMethodOpcodeValue(opcode, core->strings->__bitxor, left_value, right_value, object, is_left_side); case Program::OP_ADD: // + return pushObjectMethodOpcodeValue(opcode, core->strings->__add, left_value, right_value, object, is_left_side); case Program::OP_SUB: // - return pushObjectMethodOpcodeValue(opcode, core->strings->__sub, left_value, right_value, object, is_left_side); case Program::OP_MUL: // * return pushObjectMethodOpcodeValue(opcode, core->strings->__mul, left_value, right_value, object, is_left_side); case Program::OP_DIV: // / return pushObjectMethodOpcodeValue(opcode, core->strings->__div, left_value, right_value, object, is_left_side); case Program::OP_MOD: // % return pushObjectMethodOpcodeValue(opcode, core->strings->__mod, left_value, right_value, object, is_left_side); case Program::OP_LSHIFT: // << return pushObjectMethodOpcodeValue(opcode, core->strings->__lshift, left_value, right_value, object, is_left_side); case Program::OP_RSHIFT: // >> return pushObjectMethodOpcodeValue(opcode, core->strings->__rshift, left_value, right_value, object, is_left_side); case Program::OP_POW: // ** return pushObjectMethodOpcodeValue(opcode, core->strings->__pow, left_value, right_value, object, is_left_side); } core->pushNull(); } void pushBinaryOpcodeValue(int opcode, Value left_value, Value right_value) { switch(left_value.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: switch(right_value.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: return pushSimpleOpcodeValue(opcode, left_value, right_value); case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return pushObjectOpcodeValue(opcode, left_value, right_value, right_value.v.value, false); } break; case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: switch(right_value.type){ case OS_VALUE_TYPE_NULL: case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_STRING: // return pushObjectOpcodeValue(opcode, left_value, right_value, left_value.v.value, true); case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return pushObjectOpcodeValue(opcode, left_value, right_value, left_value.v.value, true); } } core->pushNull(); } } lib = {this}; switch(opcode){ case Program::OP_COMPARE: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber(left_value.v.number - right_value.v.number); } return pushNumber(lib.compareValues(left_value, right_value)); case Program::OP_LOGIC_PTR_EQ: return pushBool(lib.isEqualExactly(left_value, right_value)); case Program::OP_LOGIC_PTR_NE: return pushBool(!lib.isEqualExactly(left_value, right_value)); case Program::OP_LOGIC_EQ: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number == right_value.v.number); } if(left_value.type == OS_VALUE_TYPE_STRING && right_value.type == OS_VALUE_TYPE_STRING){ return pushBool(left_value.v.string == right_value.v.string); } return pushBool(lib.compareValues(left_value, right_value) == 0); case Program::OP_LOGIC_NE: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number != right_value.v.number); } if(left_value.type == OS_VALUE_TYPE_STRING && right_value.type == OS_VALUE_TYPE_STRING){ return pushBool(left_value.v.string != right_value.v.string); } return pushBool(lib.compareValues(left_value, right_value) != 0); case Program::OP_LOGIC_GE: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number >= right_value.v.number); } return pushBool(lib.compareValues(left_value, right_value) >= 0); case Program::OP_LOGIC_LE: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number <= right_value.v.number); } return pushBool(lib.compareValues(left_value, right_value) <= 0); case Program::OP_LOGIC_GREATER: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number > right_value.v.number); } return pushBool(lib.compareValues(left_value, right_value) > 0); case Program::OP_LOGIC_LESS: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushBool(left_value.v.number < right_value.v.number); } return pushBool(lib.compareValues(left_value, right_value) < 0); case Program::OP_CONCAT: if(left_value.type == OS_VALUE_TYPE_STRING && right_value.type == OS_VALUE_TYPE_STRING){ pushStringValue(newStringValue(left_value.v.string, right_value.v.string)); return; } break; case Program::OP_BIT_AND: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber((OS_INT)left_value.v.number & (OS_INT)right_value.v.number); } break; case Program::OP_BIT_OR: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber((OS_INT)left_value.v.number | (OS_INT)right_value.v.number); } break; case Program::OP_BIT_XOR: if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber((OS_INT)left_value.v.number ^ (OS_INT)right_value.v.number); } break; case Program::OP_ADD: // + if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber(left_value.v.number + right_value.v.number); } break; case Program::OP_SUB: // - if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber(left_value.v.number - right_value.v.number); } break; case Program::OP_MUL: // * if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber(left_value.v.number * right_value.v.number); } break; case Program::OP_DIV: // / if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ if(!right_value.v.number){ errorDivisionByZero(); return pushNumber(0.0); } return pushNumber(left_value.v.number / right_value.v.number); } break; case Program::OP_MOD: // % if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ if(!right_value.v.number){ errorDivisionByZero(); return pushNumber(0.0); } return pushNumber(OS_MATH_MOD_OPERATOR(left_value.v.number, right_value.v.number)); } break; case Program::OP_LSHIFT: // << if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber((OS_INT)left_value.v.number << (OS_INT)right_value.v.number); } break; case Program::OP_RSHIFT: // >> if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber((OS_INT)left_value.v.number >> (OS_INT)right_value.v.number); } break; case Program::OP_POW: // ** if(left_value.type == OS_VALUE_TYPE_NUMBER && right_value.type == OS_VALUE_TYPE_NUMBER){ return pushNumber(OS_MATH_POW_OPERATOR((OS_FLOAT)left_value.v.number, (OS_FLOAT)right_value.v.number)); } break; } return lib.pushBinaryOpcodeValue(opcode, left_value, right_value); } void OS::Core::setGlobalValue(const String& name, Value value, bool anonymous_setter_enabled, bool named_setter_enabled) { setPropertyValue(global_vars, Core::PropertyIndex(name), value, anonymous_setter_enabled, named_setter_enabled); } void OS::Core::setGlobalValue(const OS_CHAR * name, Value value, bool anonymous_setter_enabled, bool named_setter_enabled) { setGlobalValue(String(allocator, name), value, anonymous_setter_enabled, named_setter_enabled); } int OS::Core::getStackOffs(int offs) { return offs <= 0 ? stack_values.count + offs + 1 : offs; } OS::Core::Value OS::Core::getStackValue(int offs) { offs = offs <= 0 ? stack_values.count + offs : offs - 1; if(offs >= 0 && offs < stack_values.count){ return stack_values.buf[offs]; } if(offs == OS_REGISTER_GLOBALS - 1){ return global_vars; } if(offs == OS_REGISTER_USERPOOL - 1){ return user_pool; } // OS_ASSERT(false); return Value(); } OS::Core::StackValues::StackValues() { buf = NULL; capacity = 0; count = 0; } OS::Core::StackValues::~StackValues() { OS_ASSERT(!buf && !capacity && !count); } void OS::Core::reserveStackValues(int new_capacity) { if(stack_values.capacity < new_capacity){ stack_values.capacity = (stack_values.capacity*2 + 16) & ~15; if(stack_values.capacity < new_capacity){ stack_values.capacity = (new_capacity + 16) & ~15; } Value * new_buf = (Value*)malloc(sizeof(Value)*stack_values.capacity OS_DBG_FILEPOS); OS_MEMCPY(new_buf, stack_values.buf, sizeof(Value) * stack_values.count); free(stack_values.buf); stack_values.buf = new_buf; for(int i = 0; i < call_stack_funcs.count; i++){ StackFunction * stack_func = &call_stack_funcs[i]; OS_ASSERT(stack_func->locals_stack_pos >= 0); OS_ASSERT(stack_func->locals && stack_func->locals->is_stack_locals); stack_func->locals->locals = stack_values.buf + stack_func->locals_stack_pos; } if(stack_func){ stack_func_locals = stack_func->locals->locals; } } } void OS::Core::removeStackValues(int offs, int count) { if(count <= 0){ OS_ASSERT(count == 0); return; } int start = offs <= 0 ? stack_values.count + offs : offs - 1; if(start < 0 || start >= stack_values.count){ OS_ASSERT(false); return; } int end = start + count; if(end >= stack_values.count){ OS_ASSERT(end == stack_values.count); stack_values.count = start; }else{ count = stack_values.count - end; if(count == 1){ stack_values.buf[start] = stack_values.buf[end]; }else{ OS_MEMMOVE(stack_values.buf + start, stack_values.buf + end, sizeof(Value) * count); } stack_values.count -= end - start; } // gcStepIfNeeded(); } void OS::Core::removeStackValue(int offs) { removeStackValues(offs, 1); } void OS::Core::removeAllStackValues() { stack_values.count = 0; // gcStepIfNeeded(); } void OS::Core::pop(int count) { if(count >= stack_values.count){ OS_ASSERT(count == stack_values.count); stack_values.count = 0; }else{ stack_values.count -= count; } // gcStepIfNeeded(); } void OS::Core::moveStackValues(int offs, int count, int new_offs) { if(count <= 0){ OS_ASSERT(count == 0); return; } offs = offs <= 0 ? stack_values.count + offs : offs - 1; if(offs < 0 || offs >= stack_values.count){ OS_ASSERT(false); return; } int end = offs + count; if(end > stack_values.count){ OS_ASSERT(false); return; } new_offs = new_offs <= 0 ? stack_values.count + new_offs : new_offs - 1; if(new_offs < 0 || new_offs >= stack_values.count){ OS_ASSERT(false); return; } int new_end = new_offs + count; if(new_end > stack_values.count){ OS_ASSERT(false); return; } Value * temp_values = (Value*)alloca(sizeof(Value) * count); OS_MEMCPY(temp_values, stack_values.buf + offs, sizeof(Value) * count); if(new_offs > offs){ OS_MEMMOVE(stack_values.buf + offs, stack_values.buf + offs+count, sizeof(Value) * (new_offs - offs)); }else{ OS_MEMMOVE(stack_values.buf + new_offs+count, stack_values.buf + new_offs, sizeof(Value) * (offs - new_offs)); } OS_MEMCPY(stack_values.buf + new_offs, temp_values, sizeof(Value) * count); } void OS::Core::moveStackValue(int offs, int new_offs) { offs = offs <= 0 ? stack_values.count + offs : offs - 1; if(offs < 0 || offs >= stack_values.count){ OS_ASSERT(false); return; } new_offs = new_offs <= 0 ? stack_values.count + new_offs : new_offs - 1; if(new_offs < 0 || new_offs >= stack_values.count){ OS_ASSERT(false); return; } Value value = stack_values[offs]; if(new_offs > offs){ OS_MEMMOVE(stack_values.buf + offs, stack_values.buf + offs+1, sizeof(Value) * (new_offs - offs)); }else{ OS_MEMMOVE(stack_values.buf + new_offs+1, stack_values.buf + new_offs, sizeof(Value) * (offs - new_offs)); } stack_values[new_offs] = value; } void OS::Core::insertValue(Value val, int offs) { offs = offs <= 0 ? stack_values.count + offs : offs - 1; reserveStackValues(stack_values.count+1); stack_values.count++; if(offs < 0 || offs >= stack_values.count){ OS_ASSERT(false); return; } int count = stack_values.count - offs - 1; if(count > 0){ OS_MEMMOVE(stack_values.buf + offs+1, stack_values.buf + offs, sizeof(Value) * count); } stack_values[offs] = val; } void OS::pushNull() { core->pushNull(); } void OS::pushNumber(OS_INT32 val) { core->pushNumber(val); } void OS::pushNumber(OS_INT64 val) { core->pushNumber(val); } void OS::pushNumber(float val) { core->pushNumber(val); } void OS::pushNumber(double val) { core->pushNumber(val); } void OS::pushBool(bool val) { core->pushBool(val); } void OS::pushString(const OS_CHAR * val) { core->pushStringValue(val); } void OS::pushString(const OS_CHAR * val, int len) { core->pushStringValue(val, len); } void OS::pushString(const Core::String& val) { core->pushStringValue(val); } void OS::pushCFunction(OS_CFunction func, void * user_param) { core->pushCFunctionValue(func, user_param); } void OS::pushCFunction(OS_CFunction func, int closure_values, void * user_param) { core->pushCFunctionValue(func, closure_values, user_param); } void * OS::pushUserdata(int crc, int data_size, OS_UserdataDtor dtor, void * user_param) { Core::GCUserdataValue * userdata = core->pushUserdataValue(crc, data_size, dtor, user_param); return userdata ? userdata->ptr : NULL; } void * OS::pushUserdata(int data_size, OS_UserdataDtor dtor, void * user_param) { return pushUserdata(0, data_size, dtor, user_param); } void * OS::pushUserPointer(int crc, void * data, OS_UserdataDtor dtor, void * user_param) { Core::GCUserdataValue * userdata = core->pushUserPointerValue(crc, data, dtor, user_param); return userdata ? userdata->ptr : NULL; } void * OS::pushUserPointer(void * data, OS_UserdataDtor dtor, void * user_param) { return pushUserPointer(0, data, dtor, user_param); } void OS::newObject() { core->pushObjectValue(); } void OS::newArray(int initial_capacity) { core->pushArrayValue(initial_capacity); } void OS::pushStackValue(int offs) { core->pushStackValue(offs); } void OS::pushGlobals() { pushStackValue(OS_REGISTER_GLOBALS); } void OS::pushUserPool() { pushStackValue(OS_REGISTER_USERPOOL); } void OS::pushValueById(int id) { core->pushValue(core->values.get(id)); } void OS::retainValueById(int id) { Core::GCValue * value = core->values.get(id); if(value){ value->external_ref_count++; } } void OS::releaseValueById(int id) { Core::GCValue * value = core->values.get(id); if(value){ OS_ASSERT(value->external_ref_count > 0); if(!--value->external_ref_count && value->gc_color == Core::GC_WHITE){ value->gc_color = Core::GC_BLACK; } } } void OS::clone(int offs) { core->pushCloneValue(core->getStackValue(offs)); } int OS::getStackSize() { return core->stack_values.count; } int OS::getAbsoluteOffs(int offs) { return core->getStackOffs(offs); } void OS::remove(int start_offs, int count) { core->removeStackValues(start_offs, count); } void OS::pop(int count) { core->pop(count); } void OS::removeAll() { core->removeAllStackValues(); } void OS::move(int start_offs, int count, int new_offs) { core->moveStackValues(start_offs, count, new_offs); } void OS::move(int offs, int new_offs) { core->moveStackValue(offs, new_offs); } bool OS::toBool(int offs) { return core->valueToBool(core->getStackValue(offs)); } bool OS::toBool(int offs, bool def) { Core::Value value = core->getStackValue(offs); return value.isNull() ? def : core->valueToBool(value); } OS_NUMBER OS::toNumber(int offs, bool valueof_enabled) { return core->valueToNumber(core->getStackValue(offs), valueof_enabled); } OS_NUMBER OS::toNumber(int offs, OS_NUMBER def, bool valueof_enabled) { Core::Value value = core->getStackValue(offs); return value.isNull() ? def : core->valueToNumber(value, valueof_enabled); } float OS::toFloat(int offs, bool valueof_enabled) { return (float)toNumber(offs, valueof_enabled); } float OS::toFloat(int offs, float def, bool valueof_enabled) { return (float)toNumber(offs, (OS_NUMBER)def, valueof_enabled); } double OS::toDouble(int offs, bool valueof_enabled) { return (double)toNumber(offs, valueof_enabled); } double OS::toDouble(int offs, double def, bool valueof_enabled) { return (double)toNumber(offs, (OS_NUMBER)def, valueof_enabled); } int OS::toInt(int offs, bool valueof_enabled) { return (int)toNumber(offs, valueof_enabled); } int OS::toInt(int offs, int def, bool valueof_enabled) { return (int)toNumber(offs, (OS_NUMBER)def, valueof_enabled); } bool OS::isNumber(int offs, OS_NUMBER * out) { return core->isValueNumber(core->getStackValue(offs), out); } OS::String OS::toString(int offs, bool valueof_enabled) { return String(this, core->valueToString(core->getStackValue(offs), valueof_enabled)); } OS::String OS::toString(int offs, const String& def, bool valueof_enabled) { Core::Value value = core->getStackValue(offs); return value.isNull() ? def : String(this, core->valueToString(value, valueof_enabled)); } bool OS::isString(int offs, String * out) { return core->isValueString(core->getStackValue(offs), out); } bool OS::popBool() { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toBool(-1); } bool OS::popBool(bool def) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toBool(-1, def); } OS_NUMBER OS::popNumber(bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toNumber(-1, valueof_enabled); } OS_NUMBER OS::popNumber(OS_NUMBER def, bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toNumber(-1, def, valueof_enabled); } float OS::popFloat(bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toFloat(-1, valueof_enabled); } float OS::popFloat(float def, bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toFloat(-1, def, valueof_enabled); } double OS::popDouble(bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toDouble(-1, valueof_enabled); } double OS::popDouble(double def, bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toDouble(-1, def, valueof_enabled); } int OS::popInt(bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toInt(-1, valueof_enabled); } int OS::popInt(int def, bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toInt(-1, def, valueof_enabled); } OS::String OS::popString(bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toString(-1, valueof_enabled); } OS::String OS::popString(const String& def, bool valueof_enabled) { struct Pop { OS * os; ~Pop(){ os->pop(); } } pop = {this}; return toString(-1, def, valueof_enabled); } OS_EValueType OS::getType(int offs) { return core->getStackValue(offs).type; } OS_EValueType OS::getTypeById(int id) { Core::GCValue * val = core->values.get(id); return val ? val->type : OS_VALUE_TYPE_NULL; } bool OS::isType(OS_EValueType type, int offs) { return core->getStackValue(offs).type == type; } bool OS::isNull(int offs) { return isType(OS_VALUE_TYPE_NULL, offs); } bool OS::isObject(int offs) { switch(core->getStackValue(offs).type){ case OS_VALUE_TYPE_OBJECT: // case OS_VALUE_TYPE_ARRAY: return true; } return false; } bool OS::isUserdata(int crc, int offs) { Core::Value val = core->getStackValue(offs); switch(val.type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: return val.v.userdata->crc == crc; } return false; } void * OS::toUserdata(int crc, int offs) { Core::Value val = core->getStackValue(offs); switch(val.type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: if(val.v.userdata->crc == crc){ return val.v.userdata->ptr; } } return NULL; } void OS::clearUserdata(int crc, int offs) { Core::Value val = core->getStackValue(offs); switch(val.type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: if(val.v.userdata->crc == crc){ // && val.v.userdata->ptr){ core->clearValue(val.v.value); // val.v.userdata->ptr = NULL; } } } bool OS::isArray(int offs) { return isType(OS_VALUE_TYPE_ARRAY, offs); } bool OS::isFunction(int offs) { return core->getStackValue(offs).isFunction(); } bool OS::Core::isValuePrototypeOf(GCValue * val, GCValue * prototype_val) { while(val != prototype_val){ val = val->prototype; if(!val){ return false; } } return true; } bool OS::Core::isValueInstanceOf(GCValue * val, GCValue * prototype_val) { return val->prototype ? isValuePrototypeOf(val->prototype, prototype_val) : false; } bool OS::Core::isValuePrototypeOf(Value val, Value prototype_val) { GCValue * object = val.getGCValue(); GCValue * proto = prototype_val.getGCValue(); return object && proto && isValuePrototypeOf(object, proto); } bool OS::Core::isValueInstanceOf(Value val, Value prototype_val) { GCValue * object = val.getGCValue(); GCValue * proto = prototype_val.getGCValue(); return object && proto && isValueInstanceOf(object, proto); } bool OS::isPrototypeOf(int value_offs, int prototype_offs) { return core->isValuePrototypeOf(core->getStackValue(value_offs), core->getStackValue(prototype_offs)); } bool OS::is(int value_offs, int prototype_offs) { return core->isValueInstanceOf(core->getStackValue(value_offs), core->getStackValue(prototype_offs)); } void OS::setProperty(bool anonymous_setter_enabled, bool named_setter_enabled) { if(core->stack_values.count >= 3){ Core::Value object = core->stack_values[core->stack_values.count - 3]; Core::Value index = core->stack_values[core->stack_values.count - 2]; Core::Value value = core->stack_values[core->stack_values.count - 1]; core->setPropertyValue(object, Core::PropertyIndex(index), value, anonymous_setter_enabled, named_setter_enabled); pop(3); }else{ // error pop(3); } } void OS::setProperty(const OS_CHAR * name, bool anonymous_setter_enabled, bool named_setter_enabled) { setProperty(Core::String(this, name), anonymous_setter_enabled, named_setter_enabled); } void OS::setProperty(const Core::String& name, bool anonymous_setter_enabled, bool named_setter_enabled) { if(core->stack_values.count >= 2){ Core::Value object = core->stack_values[core->stack_values.count - 2]; Core::Value value = core->stack_values[core->stack_values.count - 1]; core->setPropertyValue(object, Core::PropertyIndex(name), value, anonymous_setter_enabled, named_setter_enabled); pop(2); }else{ // error pop(2); } } void OS::setProperty(int offs, const OS_CHAR * name, bool anonymous_setter_enabled, bool named_setter_enabled) { setProperty(offs, Core::String(this, name), anonymous_setter_enabled, named_setter_enabled); } void OS::setProperty(int offs, const Core::String& name, bool anonymous_setter_enabled, bool named_setter_enabled) { if(core->stack_values.count >= 1){ Core::Value object = core->getStackValue(offs); Core::Value value = core->stack_values[core->stack_values.count - 1]; core->setPropertyValue(object, Core::PropertyIndex(name), value, anonymous_setter_enabled, named_setter_enabled); pop(); }else{ // error pop(); } } void OS::addProperty() { Core::Value value = core->getStackValue(-2); switch(value.type){ case OS_VALUE_TYPE_ARRAY: core->insertValue(value.v.arr->values.count, -1); break; case OS_VALUE_TYPE_OBJECT: core->insertValue(value.v.object->table ? value.v.object->table->next_index : 0, -1); break; } setProperty(false, false); } void OS::deleteProperty(bool anonymous_del_enabled, bool named_del_enabled) { core->deleteValueProperty(core->getStackValue(-2), core->getStackValue(-1), anonymous_del_enabled, named_del_enabled, false); pop(2); } void OS::deleteProperty(const OS_CHAR * name, bool anonymous_del_enabled, bool named_del_enabled) { deleteProperty(Core::String(this, name), anonymous_del_enabled, named_del_enabled); } void OS::deleteProperty(const Core::String& name, bool anonymous_del_enabled, bool named_del_enabled) { pushString(name); deleteProperty(anonymous_del_enabled, named_del_enabled); } void OS::getPrototype() { if(core->stack_values.count >= 1){ core->pushPrototype(core->stack_values.lastElement()); }else{ pushNull(); } } void OS::setPrototype() { setPrototype(0); } void OS::setPrototype(int userdata_crc) { if(core->stack_values.count >= 2){ Core::Value value = core->stack_values[core->stack_values.count - 2]; Core::Value proto = core->stack_values[core->stack_values.count - 1]; core->setPrototype(value, proto, userdata_crc); } pop(2); } int OS::getValueId(int offs) { Core::Value val = core->getStackValue(offs); switch(val.type){ case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return val.v.value->value_id; case OS_VALUE_TYPE_WEAKREF: return val.v.value_id; } return 0; } bool OS::Core::getPropertyValue(Value& result, Table * table, const PropertyIndex& index) { #if defined OS_DEBUG && defined OS_WARN_NULL_INDEX if(table != check_recursion->table && index.index.type == OS_VALUE_TYPE_NULL){ error(OS_E_WARNING, OS_TEXT("object get null index")); } #endif if(table){ Property * prop = table->get(index); if(prop){ result = prop->value; return true; } } return false; } bool OS::Core::getPropertyValue(Value& result, GCValue * table_value, const PropertyIndex& index, bool prototype_enabled) { #if defined OS_DEBUG && defined OS_WARN_NULL_INDEX if(table_value != check_recursion && index.index.type == OS_VALUE_TYPE_NULL){ error(OS_E_WARNING, OS_TEXT("object get null index")); } #endif struct Lib { static bool getArrayIndex(Value& result, Core * core, GCValue * table_value, const PropertyIndex& index) { OS_ASSERT(dynamic_cast<GCArrayValue*>(table_value)); GCArrayValue * arr = (GCArrayValue*)table_value; int i = (int)core->valueToInt(index.index); if(i >= 0 && i < arr->values.count){ result = arr->values[i]; return true; } return false; } }; if(table_value->type == OS_VALUE_TYPE_ARRAY && index.index.type == OS_VALUE_TYPE_NUMBER){ return Lib::getArrayIndex(result, this, table_value, index); } Property * prop = NULL; Table * table = table_value->table; if(table && (prop = table->get(index))){ result = prop->value; return true; } if(prototype_enabled){ GCValue * cur_value = table_value; while(cur_value->prototype){ cur_value = cur_value->prototype; Table * cur_table = cur_value->table; if(cur_table && (prop = cur_table->get(index))){ result = prop->value; return true; } } } if(index.index.type == OS_VALUE_TYPE_STRING && strings->syntax_prototype == index.index.v.string){ result = table_value->prototype; return true; } if(table_value->type == OS_VALUE_TYPE_ARRAY){ return Lib::getArrayIndex(result, this, table_value, index); /* OS_ASSERT(dynamic_cast<GCArrayValue*>(table_value)); GCArrayValue * arr = (GCArrayValue*)table_value; int i = (int)valueToInt(index.index); if(i >= 0 && i < arr->values.count){ result = arr->values[i]; return true; } */ } return false; } bool OS::Core::getPropertyValue(Value& result, Value table_value, const PropertyIndex& index, bool prototype_enabled) { switch(table_value.type){ case OS_VALUE_TYPE_NULL: return false; case OS_VALUE_TYPE_BOOL: return prototype_enabled && getPropertyValue(result, prototypes[PROTOTYPE_BOOL], index, prototype_enabled); case OS_VALUE_TYPE_NUMBER: return prototype_enabled && getPropertyValue(result, prototypes[PROTOTYPE_NUMBER], index, prototype_enabled); case OS_VALUE_TYPE_STRING: // return prototype_enabled && getPropertyValue(result, prototypes[PROTOTYPE_STRING], index, prototype_enabled); case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return getPropertyValue(result, table_value.v.value, index, prototype_enabled); } return false; } bool OS::Core::hasProperty(GCValue * table_value, const PropertyIndex& index, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { Value value; if(getPropertyValue(value, table_value, index, prototype_enabled)){ return value.type != OS_VALUE_TYPE_NULL; } if(!anonymous_getter_enabled && !named_getter_enabled){ return false; } if(hasSpecialPrefix(index.index)){ return false; } if(index.index.type == OS_VALUE_TYPE_STRING && named_getter_enabled){ const void * buf1 = strings->__getAt.toChar(); int size1 = strings->__getAt.getDataSize(); const void * buf2 = index.index.v.string->toChar(); int size2 = index.index.v.string->getDataSize(); GCStringValue * getter_name = newStringValue(buf1, size1, buf2, size2); if(getPropertyValue(value, table_value, PropertyIndex(getter_name, PropertyIndex::KeepStringIndex()), prototype_enabled)){ return true; } } if(anonymous_getter_enabled){ // TODO: add __isset method ??? } return false; } void OS::Core::pushPropertyValue(GCValue * table_value, const PropertyIndex& index, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled, bool auto_create) { GCValue * self = table_value; for(;;){ Value value; if(getPropertyValue(value, table_value, index, prototype_enabled)){ return pushValue(value); } if((anonymous_getter_enabled || named_getter_enabled) && !hasSpecialPrefix(index.index)){ if(index.index.type == OS_VALUE_TYPE_STRING && named_getter_enabled){ const void * buf1 = strings->__getAt.toChar(); int size1 = strings->__getAt.getDataSize(); const void * buf2 = index.index.v.string->toChar(); int size2 = index.index.v.string->getDataSize(); GCStringValue * getter_name = newStringValue(buf1, size1, buf2, size2); if(getPropertyValue(value, table_value, PropertyIndex(getter_name, PropertyIndex::KeepStringIndex()), prototype_enabled)){ pushValue(value); pushValue(self); call(0, 1); return; } } if(anonymous_getter_enabled && getPropertyValue(value, table_value, PropertyIndex(strings->__get, PropertyIndex::KeepStringIndex()), prototype_enabled)){ // auto_create = false; if(value.type == OS_VALUE_TYPE_OBJECT){ table_value = value.v.value; continue; } pushValue(value); pushValue(self); pushValue(index.index); if(!auto_create){ call(1, 1); }else{ pushBool(true); call(2, 1); } if(auto_create && stack_values.lastElement().type == OS_VALUE_TYPE_NULL){ pop(); setPropertyValue(self, index, Value(pushObjectValue()), false, false); } return; } } if(auto_create){ setPropertyValue(self, index, Value(pushObjectValue()), false, false); return; } break; } return pushNull(); } void OS::Core::pushPropertyValueForPrimitive(Value self, const PropertyIndex& index, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled, bool auto_create) { GCValue * proto; switch(self.type){ case OS_VALUE_TYPE_NUMBER: proto = prototypes[PROTOTYPE_NUMBER]; break; case OS_VALUE_TYPE_BOOL: proto = prototypes[PROTOTYPE_BOOL]; break; default: pushNull(); return; } // GCValue * self = table_value; for(;;){ OS_ASSERT(proto); Value value; if(prototype_enabled && getPropertyValue(value, proto, index, prototype_enabled)){ return pushValue(value); } if((anonymous_getter_enabled || named_getter_enabled) && !hasSpecialPrefix(index.index)){ if(index.index.type == OS_VALUE_TYPE_STRING && named_getter_enabled){ const void * buf1 = strings->__getAt.toChar(); int size1 = strings->__getAt.getDataSize(); const void * buf2 = index.index.v.string->toChar(); int size2 = index.index.v.string->getDataSize(); GCStringValue * getter_name = newStringValue(buf1, size1, buf2, size2); if(getPropertyValue(value, proto, PropertyIndex(getter_name, PropertyIndex::KeepStringIndex()), prototype_enabled)){ pushValue(value); pushValue(self); call(0, 1); return; } } if(anonymous_getter_enabled && getPropertyValue(value, proto, PropertyIndex(strings->__get, PropertyIndex::KeepStringIndex()), prototype_enabled)){ // auto_create = false; if(value.type == OS_VALUE_TYPE_OBJECT){ proto = value.v.value; continue; } pushValue(value); pushValue(self); pushValue(index.index); if(!auto_create){ call(1, 1); }else{ pushBool(true); call(2, 1); } if(auto_create && stack_values.lastElement().type == OS_VALUE_TYPE_NULL){ pop(); setPropertyValue(self, index, Value(pushObjectValue()), false, false); } return; } } if(auto_create){ setPropertyValue(self, index, Value(pushObjectValue()), false, false); return; } break; } return pushNull(); } void OS::Core::pushPropertyValue(Value table_value, const PropertyIndex& index, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled, bool auto_create) { switch(table_value.type){ case OS_VALUE_TYPE_NULL: break; case OS_VALUE_TYPE_BOOL: /* if(prototype_enabled){ return pushPropertyValue(prototypes[PROTOTYPE_BOOL], index, anonymous_getter_enabled, named_getter_enabled, prototype_enabled, auto_create); } break; */ case OS_VALUE_TYPE_NUMBER: /* if(prototype_enabled){ return pushPropertyValue(prototypes[PROTOTYPE_NUMBER], index, anonymous_getter_enabled, named_getter_enabled, prototype_enabled, auto_create); } break; */ return pushPropertyValueForPrimitive(table_value, index, anonymous_getter_enabled, named_getter_enabled, prototype_enabled, auto_create); case OS_VALUE_TYPE_STRING: /* if(prototype_enabled){ return pushPropertyValue(prototypes[PROTOTYPE_STRING], index, anonymous_getter_enabled, named_getter_enabled, prototype_enabled, auto_create); } break; */ case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: return pushPropertyValue(table_value.v.value, index, anonymous_getter_enabled, named_getter_enabled, prototype_enabled, auto_create); } pushNull(); } void OS::getProperty(bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { if(core->stack_values.count >= 2){ Core::Value object = core->stack_values[core->stack_values.count - 2]; Core::Value index = core->stack_values[core->stack_values.count - 1]; // core->stack_values.count -= 2; core->pushPropertyValue(object, Core::PropertyIndex(index), anonymous_getter_enabled, named_getter_enabled, prototype_enabled, false); core->removeStackValues(-3, 2); }else{ // error pop(2); pushNull(); } } void OS::getProperty(const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { getProperty(Core::String(this, name), anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::getProperty(const Core::String& name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { pushString(name); getProperty(anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::getProperty(int offs, const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { getProperty(offs, Core::String(this, name), anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::getProperty(int offs, const Core::String& name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { pushStackValue(offs); getProperty(name, anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::Core::releaseUpvalues(Upvalues * upvalues) { if(--upvalues->ref_count > 0){ return; } deleteUpvalues(upvalues); } void OS::Core::deleteUpvalues(Upvalues * upvalues) { upvalues->prog->release(); if(upvalues->num_parents > 0){ releaseUpvalues(upvalues->getParent(0)); } if(!upvalues->is_stack_locals){ free(upvalues->locals); } free(upvalues); } void OS::Core::clearStackFunction(StackFunction * stack_func) { // OS_ASSERT(stack_func->func && stack_func->func->type == OS_VALUE_TYPE_FUNCTION); // OS_ASSERT(stack_func->func->value.func->func_decl); // OS_ASSERT(stack_func->self); // OS_ASSERT(stack_func->func->value.func->parent_inctance != stack_func); if(--stack_func->locals->ref_count > 0){ int count = stack_func->locals->num_locals; // >opcode_stack_pos - stack_func->locals_stack_pos; if(count > 0){ Value * locals = (Value*)malloc(sizeof(Value) * count OS_DBG_FILEPOS); OS_MEMCPY(locals, stack_func->locals->locals, sizeof(Value) * count); stack_func->locals->locals = locals; }else{ stack_func->locals->locals = NULL; } stack_func->locals->is_stack_locals = false; }else{ deleteUpvalues(stack_func->locals); } stack_func->func = NULL; stack_func->self = NULL; stack_func->self_for_proto = NULL; stack_func->locals = NULL; stack_func->arguments = NULL; stack_func->rest_arguments = NULL; stack_func->~StackFunction(); // free(stack_func); } void OS::Core::enterFunction(GCFunctionValue * func_value, Value self, GCValue * self_for_proto, int params, int extra_remove_from_stack, int need_ret_values) { OS_ASSERT(call_stack_funcs.count < OS_CALL_STACK_MAX_SIZE); OS_ASSERT(func_value->type == OS_VALUE_TYPE_FUNCTION); OS_ASSERT(stack_values.count >= params + extra_remove_from_stack); // OS_ASSERT(self); FunctionDecl * func_decl = func_value->func_decl; int num_extra_params = params > func_decl->num_params ? params - func_decl->num_params : 0; // int locals_mem_size = sizeof(Value) * (func_decl->num_locals + num_extra_params); // int parents_mem_size = sizeof(FunctionRunningInstance*) * func_decl->max_up_count; // stack has to be reserved here!!! don't move it reserveStackValues(stack_values.count - params + func_decl->num_locals + num_extra_params); // allocator->vectorReserveCapacity(call_stack_funcs, call_stack_funcs.count+1 OS_DBG_FILEPOS); if(call_stack_funcs.capacity < call_stack_funcs.count+1){ call_stack_funcs.capacity = call_stack_funcs.capacity > 0 ? call_stack_funcs.capacity*2 : 8; OS_ASSERT(call_stack_funcs.capacity >= call_stack_funcs.count+1); StackFunction * new_buf = (StackFunction*)malloc(sizeof(StackFunction)*call_stack_funcs.capacity OS_DBG_FILEPOS); OS_MEMCPY(new_buf, call_stack_funcs.buf, sizeof(StackFunction) * call_stack_funcs.count); free(call_stack_funcs.buf); call_stack_funcs.buf = new_buf; } // StackFunction * stack_func = new (malloc(sizeof(StackFunction) OS_DBG_FILEPOS)) StackFunction(); // StackFunction * stack_func = new (call_stack_funcs.buf + call_stack_funcs.count++) StackFunction(); StackFunction * stack_func = (StackFunction*)(call_stack_funcs.buf + call_stack_funcs.count++); stack_func->func = func_value; stack_func->self = self; stack_func->self_for_proto = self_for_proto ? self_for_proto : self.getGCValue(); if(!stack_func->self_for_proto){ switch(self.type){ case OS_VALUE_TYPE_BOOL: stack_func->self_for_proto = prototypes[PROTOTYPE_BOOL]; break; case OS_VALUE_TYPE_NUMBER: stack_func->self_for_proto = prototypes[PROTOTYPE_NUMBER]; break; } } stack_func->caller_stack_pos = stack_values.count - params - extra_remove_from_stack; stack_func->locals_stack_pos = stack_func->caller_stack_pos + extra_remove_from_stack; stack_func->stack_pos = stack_func->locals_stack_pos + func_decl->num_locals + num_extra_params; // reserveStackValues(stack_func->bottom_stack_pos); OS_ASSERT(stack_values.capacity >= stack_func->stack_pos); stack_values.count = stack_func->stack_pos; stack_func->num_params = params; stack_func->num_extra_params = num_extra_params; Upvalues * func_locals = (Upvalues*)(malloc(sizeof(Upvalues) + sizeof(Upvalues*) * func_decl->func_depth OS_DBG_FILEPOS)); func_locals->prog = func_value->prog->retain(); func_locals->func_decl = func_decl; func_locals->locals = stack_values.buf + stack_func->locals_stack_pos; func_locals->num_locals = func_decl->num_locals; func_locals->is_stack_locals = true; func_locals->num_parents = func_decl->func_depth; func_locals->ref_count = 1; func_locals->gc_time = -1; if(func_decl->func_depth > 0){ OS_ASSERT(func_value->upvalues && func_value->upvalues->num_parents == func_decl->func_depth-1); Upvalues ** parents = func_locals->getParents(); parents[0] = func_value->upvalues->retain(); if(func_decl->func_depth > 1){ OS_MEMCPY(parents+1, func_value->upvalues->getParents(), sizeof(Upvalues*) * (func_decl->func_depth-1)); } } stack_func->locals = func_locals; Value * extra_params = func_locals->locals + func_decl->num_locals; if(num_extra_params > 0 && func_decl->num_locals != params - num_extra_params){ OS_MEMCPY(extra_params, func_locals->locals + (params - num_extra_params), sizeof(Value) * num_extra_params); } int func_params = func_decl->num_params < params ? func_decl->num_params : params; OS_ASSERT(func_params <= func_decl->num_locals); if(func_decl->num_locals > func_params){ OS_MEMSET(func_locals->locals + func_params, 0, sizeof(Value) * (func_decl->num_locals - func_params)); } stack_func->need_ret_values = need_ret_values; // stack_func->opcode_offs = 0; // func_decl->opcodes_pos; new (&stack_func->opcodes) MemStreamReader(NULL, func_value->prog->opcodes->buffer + func_decl->opcodes_pos, func_decl->opcodes_size); func_locals->locals[func_decl->num_params + ENV_VAR_INDEX] = func_value->env; #ifdef OS_GLOBAL_VAR_ENABLED func_locals->locals[func_decl->num_params + GLOBALS_VAR_INDEX] = global_vars; #endif reloadStackFunctionCache(); // gcMarkStackFunction(stack_func); } int OS::Core::opBreakFunction() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= stack_func->stack_pos); int cur_ret_values = 0; int ret_values = stack_func->need_ret_values; stack_values.count = stack_func->stack_pos; ret_values = syncRetValues(ret_values, cur_ret_values); OS_ASSERT(stack_values.count == stack_func->stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; clearStackFunction(stack_func); removeStackValues(stack_func->caller_stack_pos+1, stack_values.count - ret_values - stack_func->caller_stack_pos); reloadStackFunctionCache(); return ret_values; } void OS::Core::opDebugger() { StackFunction * stack_func = this->stack_func; int line = stack_func->opcodes.readUVariable(); int pos = stack_func->opcodes.readUVariable(); int saved_lines = stack_func->opcodes.readUVariable(); const OS_CHAR * lines[OS_DEBUGGER_SAVE_NUM_LINES]; OS_MEMSET(lines, 0, sizeof(lines)); GCStringValue ** prog_strings = stack_func_prog_strings; // stack_func->func->prog->const_strings; int prog_num_strings = stack_func->func->prog->num_strings; for(int i = 0; i < saved_lines; i++){ int offs = stack_func->opcodes.readUVariable(); OS_ASSERT(offs >= 0 && offs < prog_num_strings); OS_ASSERT(prog_strings[offs]->type == OS_VALUE_TYPE_STRING); if(i < OS_DEBUGGER_SAVE_NUM_LINES){ lines[i] = prog_strings[offs]->toChar(); } } DEBUG_BREAK; } void OS::Core::opPushNumber() { // StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_numbers); pushNumber(stack_func_prog_numbers[i]); } void OS::Core::opPushString() { StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_strings); OS_ASSERT(stack_func_prog_strings[i]->type == OS_VALUE_TYPE_STRING); pushValue(stack_func_prog_strings[i]); } void OS::Core::opPushFunction() { StackFunction * stack_func = this->stack_func; int prog_func_index = stack_func->opcodes.readUVariable(); Program * prog = stack_func->func->prog; OS_ASSERT(prog_func_index > 0 && prog_func_index < prog->num_functions); FunctionDecl * func_decl = prog->functions + prog_func_index; // int env_index = stack_func->func->func_decl->num_params + ENV_VAR_INDEX; pushValue(newFunctionValue(stack_func, prog, func_decl, stack_func_locals[stack_func_env_index])); stack_func->opcodes.movePos(func_decl->opcodes_size); } void OS::Core::opPushArray() { pushArrayValue(stack_func->opcodes.readByte()); } void OS::Core::opPushObject() { pushObjectValue(); } void OS::Core::opObjectSetByAutoIndex() { OS_ASSERT(stack_values.count >= 2); Value object = stack_values[stack_values.count-2]; OS_INT num_index = 0; switch(object.type){ case OS_VALUE_TYPE_ARRAY: OS_ASSERT(dynamic_cast<GCArrayValue*>(object.v.arr)); num_index = object.v.arr->values.count; break; case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: num_index = object.v.object->table ? object.v.object->table->next_index : 0; break; } setPropertyValue(object, PropertyIndex(num_index), stack_values.lastElement(), false, false); pop(); // keep only object in stack } void OS::Core::opObjectSetByExp() { OS_ASSERT(stack_values.count >= 3); setPropertyValue(stack_values[stack_values.count - 3], Core::PropertyIndex(stack_values[stack_values.count - 2]), stack_values[stack_values.count - 1], false, false); pop(2); // keep only object in stack } void OS::Core::opObjectSetByIndex() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 2); int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_numbers); setPropertyValue(stack_values[stack_values.count-2], PropertyIndex(stack_func->func->prog->const_numbers[i]), stack_values.lastElement(), false, false); pop(); // keep only object in stack } void OS::Core::opObjectSetByName() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 2); int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_strings); GCStringValue * name = stack_func_prog_strings[i]; OS_ASSERT(name->type == OS_VALUE_TYPE_STRING); setPropertyValue(stack_values[stack_values.count-2], PropertyIndex(name, PropertyIndex::KeepStringIndex()), stack_values.lastElement(), false, false); pop(); // keep only object in stack } void OS::Core::opPushEnvVar(bool auto_create) { StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_strings); GCStringValue * name = stack_func_prog_strings[i]; OS_ASSERT(name->type == OS_VALUE_TYPE_STRING); // int env_index = stack_func->func->func_decl->num_params + ENV_VAR_INDEX; pushPropertyValue(stack_func_locals[stack_func_env_index], PropertyIndex(name, PropertyIndex::KeepStringIndex()), true, true, true, auto_create); } void OS::Core::opSetEnvVar() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i >= 0 && i < stack_func->func->prog->num_strings); GCStringValue * name = stack_func_prog_strings[i]; OS_ASSERT(name->type == OS_VALUE_TYPE_STRING); // int env_index = stack_func->func->func_decl->num_params + ENV_VAR_INDEX; setPropertyValue(stack_func_locals[stack_func_env_index], PropertyIndex(name, PropertyIndex::KeepStringIndex()), stack_values.lastElement(), true, true); pop(); } void OS::Core::opPushThis() { StackFunction * stack_func = this->stack_func; pushValue(stack_func->self); } void OS::Core::opPushArguments() { StackFunction * stack_func = this->stack_func; pushArguments(stack_func); } void OS::Core::opPushRestArguments() { StackFunction * stack_func = this->stack_func; pushRestArguments(stack_func); } void OS::Core::opPushLocalVar() { int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i < num_stack_func_locals); pushValue(stack_func_locals[i]); } void OS::Core::opPushLocalVarAutoCreate() { // StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); OS_ASSERT(i < num_stack_func_locals); if(stack_func_locals[i].type == OS_VALUE_TYPE_NULL){ stack_func_locals[i] = newObjectValue(); } pushValue(stack_func_locals[i]); } void OS::Core::opSetLocalVar() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); int i = stack_func->opcodes.readUVariable(); // Upvalues * func_upvalues = stack_func->locals; OS_ASSERT(i < num_stack_func_locals); switch((stack_func_locals[i] = stack_values.lastElement()).type){ case OS_VALUE_TYPE_FUNCTION: OS_ASSERT(dynamic_cast<GCFunctionValue*>(stack_func_locals[i].v.func)); if(!stack_func_locals[i].v.func->name){ stack_func_locals[i].v.func->name = stack_func->func->func_decl->locals[i].name.string; } break; case OS_VALUE_TYPE_CFUNCTION: OS_ASSERT(dynamic_cast<GCCFunctionValue*>(stack_func_locals[i].v.cfunc)); if(!stack_func_locals[i].v.cfunc->name){ stack_func_locals[i].v.cfunc->name = stack_func->func->func_decl->locals[i].name.string; } break; } pop(); } void OS::Core::opPushUpvalue() { StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); int up_count = stack_func->opcodes.readByte(); OS_ASSERT(up_count <= stack_func->func->func_decl->max_up_count); Upvalues * func_upvalues = stack_func->locals; OS_ASSERT(up_count <= func_upvalues->num_parents); Upvalues * scope = func_upvalues->getParent(up_count-1); OS_ASSERT(i < scope->num_locals); pushValue(scope->locals[i]); } void OS::Core::opPushUpvalueAutoCreate() { StackFunction * stack_func = this->stack_func; int i = stack_func->opcodes.readUVariable(); int up_count = stack_func->opcodes.readByte(); OS_ASSERT(up_count <= stack_func->func->func_decl->max_up_count); Upvalues * func_upvalues = stack_func->locals; OS_ASSERT(up_count <= func_upvalues->num_parents); Upvalues * scope = func_upvalues->getParent(up_count-1); OS_ASSERT(i < scope->num_locals); if(scope->locals[i].type == OS_VALUE_TYPE_NULL){ scope->locals[i] = newObjectValue(); } pushValue(scope->locals[i]); } void OS::Core::opSetUpvalue() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); int i = stack_func->opcodes.readUVariable(); int up_count = stack_func->opcodes.readByte(); OS_ASSERT(up_count <= stack_func->func->func_decl->max_up_count); Upvalues * func_upvalues = stack_func->locals; OS_ASSERT(up_count <= func_upvalues->num_parents); Upvalues * scope = func_upvalues->getParent(up_count-1); OS_ASSERT(i < scope->num_locals); switch((scope->locals[i] = stack_values.lastElement()).type){ case OS_VALUE_TYPE_FUNCTION: OS_ASSERT(dynamic_cast<GCFunctionValue*>(scope->locals[i].v.func)); if(!scope->locals[i].v.func->name){ scope->locals[i].v.func->name = scope->func_decl->locals[i].name.string; } break; case OS_VALUE_TYPE_CFUNCTION: OS_ASSERT(dynamic_cast<GCCFunctionValue*>(scope->locals[i].v.cfunc)); if(!scope->locals[i].v.cfunc->name){ scope->locals[i].v.cfunc->name = scope->func_decl->locals[i].name.string; } break; } pop(); } void OS::Core::opIfJump(bool boolean) { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); // Value value = stack_values.lastElement(); int offs = stack_func->opcodes.readInt32(); if(valueToBool(stack_values.lastElement()) == boolean){ stack_func->opcodes.movePos(offs); } pop(); } void OS::Core::opJump() { StackFunction * stack_func = this->stack_func; int offs = stack_func->opcodes.readInt32(); stack_func->opcodes.movePos(offs); } void OS::Core::opCall() { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int params = buf[0]; int ret_values = buf[1]; #else int params = stack_func->opcodes.readByte(); int ret_values = stack_func->opcodes.readByte(); #endif OS_ASSERT(stack_values.count >= 2 + params); // insertValue(Value(), -params); call(params, ret_values, NULL, true); } void OS::Core::opSuperCall(int& break_with_ret_values) { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int params = buf[0]; int ret_values = buf[1]; #else int params = stack_func->opcodes.readByte(); int ret_values = stack_func->opcodes.readByte(); #endif OS_ASSERT(stack_values.count >= 2+params); OS_ASSERT(stack_values.buf[stack_values.count-2-params].type == OS_VALUE_TYPE_NULL); OS_ASSERT(stack_values.buf[stack_values.count-1-params].type == OS_VALUE_TYPE_NULL); GCFunctionValue * func_value = stack_func->func; if(stack_func->self_for_proto && func_value->name){ GCValue * proto = stack_func->self_for_proto->prototype; if(stack_func->self_for_proto->is_object_instance){ proto = proto ? proto->prototype : NULL; } if(proto){ bool prototype_enabled = true; Value func; if(getPropertyValue(func, proto, PropertyIndex(func_value->name, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { bool is_constructor = func_value->name == strings->__construct.string; stack_values.buf[stack_values.count-2-params] = func; stack_values.buf[stack_values.count-1-params] = stack_func->self; int func_ret_values = call(params, is_constructor && !ret_values ? 1 : ret_values, proto); if(is_constructor){ GCValue * new_self = stack_values.lastElement().getGCValue(); if(!new_self){ int cur_ret_values = 0; int ret_values = stack_func->need_ret_values; ret_values = syncRetValues(ret_values, cur_ret_values); // OS_ASSERT(stack_values.count == stack_func->bottom_stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; int caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - ret_values - caller_stack_pos); reloadStackFunctionCache(); break_with_ret_values = ret_values; return; } if(new_self != stack_func->self.getGCValue()){ stack_func->self = new_self; stack_func->self_for_proto = new_self; } } syncRetValues(ret_values, func_ret_values); return; } } } pop(2+params); syncRetValues(ret_values, 0); } void OS::Core::opTailCall(int& out_ret_values) { StackFunction * stack_func = this->stack_func; int params = stack_func->opcodes.readByte(); int ret_values = stack_func->need_ret_values; OS_ASSERT(stack_values.count >= 1 + params); Value func_value = stack_values[stack_values.count-1-params]; OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); switch(func_value.type){ case OS_VALUE_TYPE_CFUNCTION: case OS_VALUE_TYPE_OBJECT: // pushNull(); // moveStackValue(-1, -params); insertValue(Value(), -params); call(params, ret_values); break; case OS_VALUE_TYPE_FUNCTION: { call_stack_funcs.count--; int caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - 1-params - caller_stack_pos); enterFunction(func_value.v.func, NULL, NULL, params, 1, ret_values); return; } default: // TODO: warn or error here??? pop(1+params); ret_values = syncRetValues(ret_values, 0); } OS_ASSERT(stack_values.count == stack_func->stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; int caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - ret_values - caller_stack_pos); reloadStackFunctionCache(); out_ret_values = ret_values; } void OS::Core::opCallMethod() { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int params = buf[0]; int ret_values = buf[1]; #else int params = stack_func->opcodes.readByte(); int ret_values = stack_func->opcodes.readByte(); #endif OS_ASSERT(stack_values.count >= 2 + params); Value table_value = stack_values[stack_values.count-2-params]; pushPropertyValue(table_value, PropertyIndex(stack_values[stack_values.count-1-params]), true, true, true, false); #if 1 stack_values[stack_values.count-2-params-1] = stack_values.lastElement(); stack_values[stack_values.count-2-params-0] = table_value; stack_values.count--; call(params, ret_values, NULL, true); #else pushValue(table_value); moveStackValues(-2, 2, -2-params); call(params, ret_values); removeStackValues(-2-ret_values, 2); return false; #endif } void OS::Core::opTailCallMethod(int& out_ret_values) { StackFunction * stack_func = this->stack_func; int params = stack_func->opcodes.readByte(); int ret_values = stack_func->need_ret_values; OS_ASSERT(stack_values.count >= 2 + params); Value table_value = stack_values[stack_values.count-2-params]; pushPropertyValue(table_value, Core::PropertyIndex(stack_values[stack_values.count-1-params]), true, true, true, false); Value func_value = stack_values.lastElement(); GCValue * self = stack_func->self.getGCValue(); GCValue * self_for_proto = stack_func->self_for_proto; GCValue * call_self = table_value.getGCValue(); if(call_self && (!self || self->prototype != call_self)){ self = call_self; self_for_proto = call_self; } pushValue(self); moveStackValues(-2, 2, -2-params); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); int caller_stack_pos; switch(func_value.type){ case OS_VALUE_TYPE_CFUNCTION: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: call(params, ret_values); removeStackValues(-2-ret_values, 2); break; case OS_VALUE_TYPE_FUNCTION: call_stack_funcs.count--; caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - 4-params - caller_stack_pos); enterFunction(func_value.v.func, self, self_for_proto, params, 4, ret_values); return; default: // TODO: warn or error here??? pop(4+params); ret_values = syncRetValues(ret_values, 0); } OS_ASSERT(stack_values.count == stack_func->stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - ret_values - caller_stack_pos); reloadStackFunctionCache(); out_ret_values = ret_values; } int OS::Core::opReturn() { StackFunction * stack_func = this->stack_func; int cur_ret_values = stack_func->opcodes.readByte(); int ret_values = stack_func->need_ret_values; ret_values = syncRetValues(ret_values, cur_ret_values); OS_ASSERT(stack_values.count == stack_func->stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; int caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - ret_values - caller_stack_pos); reloadStackFunctionCache(); return ret_values; } int OS::Core::opReturnAuto() { StackFunction * stack_func = this->stack_func; int cur_ret_values = 0; int ret_values = stack_func->need_ret_values; GCFunctionValue * func_value = stack_func->func; if(ret_values > 0 && func_value->name && func_value->name == strings->__construct.string){ pushValue(stack_func->self); cur_ret_values = 1; } ret_values = syncRetValues(ret_values, cur_ret_values); // OS_ASSERT(stack_values.count == stack_func->stack_pos + ret_values); // stack_func->opcodes_pos = opcodes.getPos(); OS_ASSERT(call_stack_funcs.count > 0 && &call_stack_funcs[call_stack_funcs.count-1] == stack_func); call_stack_funcs.count--; int caller_stack_pos = stack_func->caller_stack_pos; clearStackFunction(stack_func); removeStackValues(caller_stack_pos+1, stack_values.count - ret_values - caller_stack_pos); reloadStackFunctionCache(); return ret_values; } void OS::Core::opGetProperty(bool auto_create) { StackFunction * stack_func = this->stack_func; int ret_values = stack_func->opcodes.readByte(); OS_ASSERT(stack_values.count >= 2); pushPropertyValue(stack_values.buf[stack_values.count - 2], PropertyIndex(stack_values.buf[stack_values.count - 1]), true, true, true, auto_create); removeStackValues(-3, 2); // OS_ASSERT(ret_values == 1); syncRetValues(ret_values, 1); } void OS::Core::opGetPropertyByLocals(bool auto_create) { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 3 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 3; int ret_values = buf[0]; int local_1 = buf[1]; int local_2 = buf[2]; #else int ret_values = stack_func->opcodes.readByte(); int local_1 = stack_func->opcodes.readByte(); int local_2 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals && local_2 < num_stack_func_locals); pushPropertyValue(stack_func_locals[local_1], PropertyIndex(stack_func_locals[local_2]), true, true, true, auto_create); // OS_ASSERT(ret_values == 1); syncRetValues(ret_values, 1); } void OS::Core::opGetPropertyByLocalAndNumber(bool auto_create) { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int ret_values = buf[0]; int local_1 = buf[1]; #else int ret_values = stack_func->opcodes.readByte(); int local_1 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals); int number_index = stack_func->opcodes.readUVariable(); OS_ASSERT(number_index >= 0 && number_index < stack_func->func->prog->num_numbers); pushPropertyValue(stack_func_locals[local_1], PropertyIndex(stack_func_prog_numbers[number_index]), true, true, true, auto_create); // OS_ASSERT(ret_values == 1); syncRetValues(ret_values, 1); } void OS::Core::opSetProperty() { OS_ASSERT(stack_values.count >= 3); setPropertyValue(stack_values.buf[stack_values.count - 2], PropertyIndex(stack_values.buf[stack_values.count - 1]), stack_values.buf[stack_values.count - 3], true, true); pop(3); } void OS::Core::opSetPropertyByLocals(bool auto_create) { OS_ASSERT(stack_values.count >= 1); #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int local_1 = buf[0]; int local_2 = buf[1]; #else int local_1 = stack_func->opcodes.readByte(); int local_2 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals && local_2 < num_stack_func_locals); if(auto_create && stack_func_locals[local_1].type == OS_VALUE_TYPE_NULL){ stack_func_locals[local_1] = newObjectValue(); } setPropertyValue(stack_func_locals[local_1], PropertyIndex(stack_func_locals[local_2]), stack_values.lastElement(), true, true); pop(); } void OS::Core::opGetSetPropertyByLocals(bool auto_create) { OS_ASSERT(stack_values.count >= 1); #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 4 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 4; int local_1 = buf[0]; int local_2 = buf[1]; #else int local_1 = stack_func->opcodes.readByte(); int local_2 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals && local_2 < num_stack_func_locals); pushPropertyValue(stack_func_locals[local_1], PropertyIndex(stack_func_locals[local_2]), true, true, true, auto_create); #if 1 local_1 = buf[2]; local_2 = buf[3]; #else local_1 = stack_func->opcodes.readByte(); local_2 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals && local_2 < num_stack_func_locals); if(auto_create && stack_func_locals[local_1].type == OS_VALUE_TYPE_NULL){ stack_func_locals[local_1] = newObjectValue(); } setPropertyValue(stack_func_locals[local_1], PropertyIndex(stack_func_locals[local_2]), stack_values.lastElement(), true, true); pop(); } void OS::Core::opSetDim() { StackFunction * stack_func = this->stack_func; int params = stack_func->opcodes.readByte(); OS_ASSERT(stack_values.count >= 2 + params); moveStackValue(-2-params, -1-params); // put value to the first param params++; Value table_value = stack_values[stack_values.count-1-params]; Value func; if(getPropertyValue(func, table_value, PropertyIndex(params == 1 ? strings->__setempty : strings->__setdim, PropertyIndex::KeepStringIndex()), true) && func.isFunction()) { #if 1 insertValue(func, -1-params); call(params, 0, NULL, true); #else pushValue(func); pushValue(table_value); moveStackValues(-2, 2, -2-params); // put func value before params call(params, 0); removeStackValue(-1); // remove table_value #endif }else{ pop(params+1); } } void OS::Core::opExtends() { OS_ASSERT(stack_values.count >= 2); Value right_value = stack_values.lastElement(); switch(right_value.type){ case OS_VALUE_TYPE_NULL: // null value has no prototype break; case OS_VALUE_TYPE_BOOL: case OS_VALUE_TYPE_NUMBER: break; case OS_VALUE_TYPE_STRING: case OS_VALUE_TYPE_ARRAY: case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_FUNCTION: right_value.v.value->prototype = stack_values[stack_values.count-2].getGCValue(); break; case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_CFUNCTION: // TODO: warning??? break; } removeStackValue(-2); } void OS::Core::opClone() { OS_ASSERT(stack_values.count >= 1); pushCloneValue(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opDeleteProperty() { OS_ASSERT(stack_values.count >= 2); deleteValueProperty(stack_values[stack_values.count-2], stack_values.lastElement(), true, true, false); pop(2); } void OS::Core::opLogicAnd() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); int offs = stack_func->opcodes.readInt32(); if(!valueToBool(stack_values.lastElement())){ stack_func->opcodes.movePos(offs); }else{ pop(); } } void OS::Core::opLogicOr() { StackFunction * stack_func = this->stack_func; OS_ASSERT(stack_values.count >= 1); int offs = stack_func->opcodes.readInt32(); if(valueToBool(stack_values.lastElement())){ stack_func->opcodes.movePos(offs); }else{ pop(); } } void OS::Core::opSuper() { StackFunction * stack_func = this->stack_func; if(stack_func->self_for_proto){ GCValue * proto = stack_func->self_for_proto->prototype; if(stack_func->self_for_proto->is_object_instance){ proto = proto ? proto->prototype : NULL; } pushValue(proto); }else{ pushNull(); } } void OS::Core::opTypeOf() { OS_ASSERT(stack_values.count >= 1); pushTypeOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opValueOf() { OS_ASSERT(stack_values.count >= 1); pushValueOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opNumberOf() { OS_ASSERT(stack_values.count >= 1); pushNumberOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opStringOf() { OS_ASSERT(stack_values.count >= 1); pushStringOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opArrayOf() { OS_ASSERT(stack_values.count >= 1); pushArrayOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opObjectOf() { OS_ASSERT(stack_values.count >= 1); pushObjectOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opUserdataOf() { OS_ASSERT(stack_values.count >= 1); pushUserdataOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opFunctionOf() { OS_ASSERT(stack_values.count >= 1); pushFunctionOf(stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opBooleanOf(bool b) { OS_ASSERT(stack_values.count >= 1); stack_values.lastElement() = valueToBool(stack_values.lastElement()) == b; } void OS::Core::opIn() { OS_ASSERT(stack_values.count >= 2); Core::GCValue * self = stack_values.lastElement().getGCValue(); bool has_property = self && hasProperty(self, stack_values[stack_values.count-2], true, true, true); pop(2); pushBool(has_property); } void OS::Core::opIsPrototypeOf() { OS_ASSERT(stack_values.count >= 2); bool ret = isValuePrototypeOf(stack_values[stack_values.count-2], stack_values.lastElement()); pop(2); pushBool(ret); } void OS::Core::opIs() { OS_ASSERT(stack_values.count >= 2); bool ret = isValueInstanceOf(stack_values[stack_values.count-2], stack_values.lastElement()); pop(2); pushBool(ret); } void OS::Core::opLength() { OS_ASSERT(stack_values.count >= 1); Value value = stack_values.lastElement(); bool prototype_enabled = true; Value func; if(getPropertyValue(func, value, PropertyIndex(strings->__len, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { pushValue(func); pushValue(value); call(0, 1); }else{ pushNull(); } removeStackValue(-2); } void OS::Core::opUnaryOperator(int opcode) { OS_ASSERT(stack_values.count >= 1); pushOpResultValue(opcode, stack_values.lastElement()); removeStackValue(-2); } void OS::Core::opBinaryOperator(int opcode) { OS_ASSERT(stack_values.count >= 2); pushOpResultValue(opcode, stack_values[stack_values.count-2], stack_values.lastElement()); removeStackValues(-3, 2); } void OS::Core::opBinaryOperatorByLocals() { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 3 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 3; int opcode = buf[0]; int local_1 = buf[1]; int local_2 = buf[2]; #else int opcode = stack_func->opcodes.readByte(); int local_1 = stack_func->opcodes.readByte(); int local_2 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals && local_2 < num_stack_func_locals); Value * stack_func_locals = this->stack_func_locals; pushOpResultValue(opcode, stack_func_locals[local_1], stack_func_locals[local_2]); } void OS::Core::opBinaryOperatorByLocalAndNumber() { StackFunction * stack_func = this->stack_func; #if 1 OS_ASSERT(stack_func->opcodes.getPos() + 2 <= stack_func->opcodes.size); OS_BYTE * buf = stack_func->opcodes.cur; stack_func->opcodes.cur += 2; int opcode = buf[0]; int local_1 = buf[1]; #else int opcode = stack_func->opcodes.readByte(); int local_1 = stack_func->opcodes.readByte(); #endif OS_ASSERT(local_1 < num_stack_func_locals); int number_index = stack_func->opcodes.readUVariable(); OS_ASSERT(number_index >= 0 && number_index < stack_func->func->prog->num_numbers); pushOpResultValue(opcode, stack_func_locals[local_1], stack_func_prog_numbers[number_index]); } void OS::Core::reloadStackFunctionCache() { if(call_stack_funcs.count > 0){ stack_func = &call_stack_funcs.lastElement(); stack_func_locals = stack_func->locals->locals; num_stack_func_locals = stack_func->locals->num_locals; stack_func_env_index = stack_func->func->func_decl->num_params + ENV_VAR_INDEX; stack_func_prog_numbers = stack_func->func->prog->const_numbers; stack_func_prog_strings = stack_func->func->prog->const_strings; }else{ stack_func = NULL; stack_func_locals = NULL; num_stack_func_locals = 0; stack_func_env_index = 0; stack_func_prog_numbers = NULL; stack_func_prog_strings = NULL; } } int OS::Core::execute() { #ifdef OS_DEBUG allocator->checkNativeStackUsage(OS_TEXT("OS::Core::execute")); #endif int i, ret_values, ret_stack_funcs = call_stack_funcs.count-1; #ifdef OS_INFINITE_LOOP_OPCODES for(int opcodes_executed = 0;; opcodes_executed++){ #else for(;;){ #endif // StackFunction * stack_func = &call_stack_funcs.lastElement(); // could be invalid because of stack resize OS_ASSERT(stack_values.count >= stack_func->stack_pos); // stack_func->opcode_offs = opcodes.pos; // used by debugger to show currect position if debug info present if(terminated #ifdef OS_INFINITE_LOOP_OPCODES || opcodes_executed >= OS_INFINITE_LOOP_OPCODES #endif ) { break; } Program::OpcodeType opcode = (Program::OpcodeType)stack_func->opcodes.readByte(); OS_PROFILE_BEGIN_OPCODE(opcode); switch(opcode){ default: error(OS_E_ERROR, "Unknown opcode, program is corrupted!!!"); allocator->setTerminated(); break; case Program::OP_DEBUGGER: opDebugger(); break; case Program::OP_PUSH_NUMBER: opPushNumber(); break; case Program::OP_PUSH_STRING: opPushString(); break; case Program::OP_PUSH_NULL: pushNull(); break; case Program::OP_PUSH_TRUE: pushBool(true); break; case Program::OP_PUSH_FALSE: pushBool(false); break; case Program::OP_PUSH_FUNCTION: opPushFunction(); break; case Program::OP_PUSH_NEW_ARRAY: opPushArray(); break; case Program::OP_PUSH_NEW_OBJECT: opPushObject(); break; case Program::OP_OBJECT_SET_BY_AUTO_INDEX: opObjectSetByAutoIndex(); break; case Program::OP_OBJECT_SET_BY_EXP: opObjectSetByExp(); break; case Program::OP_OBJECT_SET_BY_INDEX: opObjectSetByIndex(); break; case Program::OP_OBJECT_SET_BY_NAME: opObjectSetByName(); break; case Program::OP_PUSH_ENV_VAR: case Program::OP_PUSH_ENV_VAR_AUTO_CREATE: opPushEnvVar(opcode == Program::OP_PUSH_ENV_VAR_AUTO_CREATE); break; case Program::OP_SET_ENV_VAR: opSetEnvVar(); break; case Program::OP_PUSH_THIS: opPushThis(); break; case Program::OP_PUSH_ARGUMENTS: opPushArguments(); break; case Program::OP_PUSH_REST_ARGUMENTS: opPushRestArguments(); break; case Program::OP_PUSH_LOCAL_VAR: i = stack_func->opcodes.readByte(); OS_ASSERT(i < num_stack_func_locals); pushValue(stack_func_locals[i]); break; case Program::OP_PUSH_LOCAL_VAR_BY_AUTO_INDEX: opPushLocalVar(); break; case Program::OP_PUSH_LOCAL_VAR_AUTO_CREATE: opPushLocalVarAutoCreate(); break; case Program::OP_SET_LOCAL_VAR: opSetLocalVar(); break; case Program::OP_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCALS: opBinaryOperatorByLocals(); opSetLocalVar(); break; case Program::OP_SET_LOCAL_VAR_BY_BIN_OPERATOR_LOCAL_AND_NUMBER: opBinaryOperatorByLocalAndNumber(); opSetLocalVar(); break; case Program::OP_PUSH_UP_LOCAL_VAR: opPushUpvalue(); break; case Program::OP_PUSH_UP_LOCAL_VAR_AUTO_CREATE: opPushUpvalueAutoCreate(); break; case Program::OP_SET_UP_LOCAL_VAR: opSetUpvalue(); break; case Program::OP_IF_NOT_JUMP: opIfJump(false); break; case Program::OP_IF_JUMP: opIfJump(true); break; case Program::OP_JUMP: opJump(); break; case Program::OP_CALL: opCall(); break; case Program::OP_SUPER_CALL: OS_PROFILE_END_OPCODE(opcode); // we shouldn't profile call here opSuperCall(ret_values); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); return ret_values; } continue; case Program::OP_TAIL_CALL: OS_PROFILE_END_OPCODE(opcode); // we shouldn't profile call here opTailCall(ret_values); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); return ret_values; } continue; case Program::OP_CALL_METHOD: OS_PROFILE_END_OPCODE(opcode); // we shouldn't profile call here opCallMethod(); continue; case Program::OP_TAIL_CALL_METHOD: OS_PROFILE_END_OPCODE(opcode); // we shouldn't profile call here opTailCallMethod(ret_values); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); return ret_values; } continue; case Program::OP_RETURN: ret_values = opReturn(); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); OS_PROFILE_END_OPCODE(opcode); return ret_values; } break; case Program::OP_RETURN_AUTO: ret_values = opReturnAuto(); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); OS_PROFILE_END_OPCODE(opcode); return ret_values; } break; case Program::OP_GET_PROPERTY: opGetProperty(false); break; case Program::OP_GET_PROPERTY_AUTO_CREATE: opGetProperty(true); break; case Program::OP_GET_PROPERTY_BY_LOCALS: opGetPropertyByLocals(false); break; case Program::OP_GET_PROPERTY_BY_LOCAL_AND_NUMBER: opGetPropertyByLocalAndNumber(false); break; case Program::OP_SET_PROPERTY: opSetProperty(); break; case Program::OP_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: opSetPropertyByLocals(true); break; case Program::OP_GET_SET_PROPERTY_BY_LOCALS_AUTO_CREATE: opGetSetPropertyByLocals(true); break; case Program::OP_SET_DIM: opSetDim(); break; case Program::OP_EXTENDS: opExtends(); break; case Program::OP_CLONE: opClone(); break; case Program::OP_DELETE_PROP: opDeleteProperty(); break; case Program::OP_POP: pop(); break; case Program::OP_LOGIC_AND: opLogicAnd(); break; case Program::OP_LOGIC_OR: opLogicOr(); break; case Program::OP_SUPER: opSuper(); break; case Program::OP_TYPE_OF: opTypeOf(); break; case Program::OP_VALUE_OF: opValueOf(); break; case Program::OP_NUMBER_OF: opNumberOf(); break; case Program::OP_STRING_OF: opStringOf(); break; case Program::OP_ARRAY_OF: opArrayOf(); break; case Program::OP_OBJECT_OF: opObjectOf(); break; case Program::OP_USERDATA_OF: opUserdataOf(); break; case Program::OP_FUNCTION_OF: opFunctionOf(); break; case Program::OP_LOGIC_BOOL: case Program::OP_LOGIC_NOT: opBooleanOf(opcode == Program::OP_LOGIC_BOOL); break; case Program::OP_IN: opIn(); break; case Program::OP_ISPROTOTYPEOF: opIsPrototypeOf(); break; case Program::OP_IS: opIs(); break; case Program::OP_LENGTH: opLength(); break; case Program::OP_BIT_NOT: case Program::OP_PLUS: case Program::OP_NEG: opUnaryOperator(opcode); break; case Program::OP_BIN_OPERATOR_BY_LOCALS: opBinaryOperatorByLocals(); break; case Program::OP_BIN_OPERATOR_BY_LOCAL_AND_NUMBER: opBinaryOperatorByLocalAndNumber(); break; case Program::OP_CONCAT: case Program::OP_LOGIC_PTR_EQ: case Program::OP_LOGIC_PTR_NE: case Program::OP_LOGIC_EQ: case Program::OP_LOGIC_NE: case Program::OP_LOGIC_GE: case Program::OP_LOGIC_LE: case Program::OP_LOGIC_GREATER: case Program::OP_LOGIC_LESS: case Program::OP_BIT_AND: case Program::OP_BIT_OR: case Program::OP_BIT_XOR: case Program::OP_ADD: // + case Program::OP_SUB: // - case Program::OP_MUL: // * case Program::OP_DIV: // / case Program::OP_MOD: // % case Program::OP_LSHIFT: // << case Program::OP_RSHIFT: // >> case Program::OP_POW: // ** opBinaryOperator(opcode); break; } OS_PROFILE_END_OPCODE(opcode); } for(;;){ ret_values = opBreakFunction(); if(ret_stack_funcs >= call_stack_funcs.count){ OS_ASSERT(ret_stack_funcs == call_stack_funcs.count); return ret_values; } } return 0; } void OS::runOp(OS_EOpcode opcode) { struct Lib { Core * core; void runBinaryOpcode(int opcode) { int count = core->stack_values.count; if(count < 2){ core->pushNull(); return; } Core::Value left_value = core->stack_values[count-2]; Core::Value right_value = core->stack_values[count-1]; // core->stack_values.count -= 2; core->pushOpResultValue(opcode, left_value, right_value); core->removeStackValues(-3, 2); } void runUnaryOpcode(int opcode) { int count = core->stack_values.count; if(count < 1){ core->pushNull(); return; } Core::Value value = core->stack_values[count-1]; core->pushOpResultValue(opcode, value); core->removeStackValue(-2); } } lib = {core}; switch(opcode){ case OP_COMPARE: return lib.runBinaryOpcode(Core::Program::OP_COMPARE); case OP_LOGIC_PTR_EQ: // === return lib.runBinaryOpcode(Core::Program::OP_LOGIC_PTR_EQ); case OP_LOGIC_PTR_NE: // !== return lib.runBinaryOpcode(Core::Program::OP_LOGIC_PTR_NE); case OP_LOGIC_EQ: // == return lib.runBinaryOpcode(Core::Program::OP_LOGIC_EQ); case OP_LOGIC_NE: // != return lib.runBinaryOpcode(Core::Program::OP_LOGIC_NE); case OP_LOGIC_GE: // >= return lib.runBinaryOpcode(Core::Program::OP_LOGIC_GE); case OP_LOGIC_LE: // <= return lib.runBinaryOpcode(Core::Program::OP_LOGIC_LE); case OP_LOGIC_GREATER: // > return lib.runBinaryOpcode(Core::Program::OP_LOGIC_GREATER); case OP_LOGIC_LESS: // < return lib.runBinaryOpcode(Core::Program::OP_LOGIC_LESS); case OP_BIT_AND: // & return lib.runBinaryOpcode(Core::Program::OP_BIT_AND); case OP_BIT_OR: // | return lib.runBinaryOpcode(Core::Program::OP_BIT_OR); case OP_BIT_XOR: // ^ return lib.runBinaryOpcode(Core::Program::OP_BIT_XOR); case OP_ADD: // + return lib.runBinaryOpcode(Core::Program::OP_ADD); case OP_SUB: // - return lib.runBinaryOpcode(Core::Program::OP_SUB); case OP_MUL: // * return lib.runBinaryOpcode(Core::Program::OP_MUL); case OP_DIV: // / return lib.runBinaryOpcode(Core::Program::OP_DIV); case OP_MOD: // % return lib.runBinaryOpcode(Core::Program::OP_MOD); case OP_LSHIFT: // << return lib.runBinaryOpcode(Core::Program::OP_LSHIFT); case OP_RSHIFT: // >> return lib.runBinaryOpcode(Core::Program::OP_RSHIFT); case OP_POW: // ** return lib.runBinaryOpcode(Core::Program::OP_POW); case OP_CONCAT: // .. return lib.runBinaryOpcode(Core::Program::OP_CONCAT); case OP_BIT_NOT: // ~ return lib.runUnaryOpcode(Core::Program::OP_BIT_NOT); case OP_PLUS: // + return lib.runUnaryOpcode(Core::Program::OP_PLUS); case OP_NEG: // - return lib.runUnaryOpcode(Core::Program::OP_NEG); case OP_LENGTH: // # return lib.runUnaryOpcode(Core::Program::OP_LENGTH); /* case OP_LOGIC_BOOL: return lib.runUnaryOpcode(Core::Program::OP_LOGIC_BOOL); case OP_LOGIC_NOT: return lib.runUnaryOpcode(Core::Program::OP_LOGIC_NOT); case OP_VALUE_OF: return lib.runUnaryOpcode(Core::Program::OP_VALUE_OF); case OP_NUMBER_OF: return lib.runUnaryOpcode(Core::Program::OP_NUMBER_OF); case OP_STRING_OF: return lib.runUnaryOpcode(Core::Program::OP_STRING_OF); case OP_ARRAY_OF: return lib.runUnaryOpcode(Core::Program::OP_ARRAY_OF); case OP_OBJECT_OF: return lib.runUnaryOpcode(Core::Program::OP_OBJECT_OF); case OP_USERDATA_OF: return lib.runUnaryOpcode(Core::Program::OP_USERDATA_OF); case OP_FUNCTION_OF: return lib.runUnaryOpcode(Core::Program::OP_FUNCTION_OF); case OP_CLONE: return lib.runUnaryOpcode(Core::Program::OP_CLONE); */ } pushNull(); } int OS::getLen(int offs) { pushStackValue(offs); runOp(OP_LENGTH); return popInt(); } void OS::getErrorHandler(int code) { for(int i = 0; i < OS_ERROR_LEVELS; i++){ if(code & (1<<i)){ core->pushValue(core->error_handlers[i]); return; } } pushNull(); } void OS::setErrorHandler(int code) { bool returned = false; Core::Value func = core->getStackValue(-1); if(func.isFunction()){ for(int i = 0; i < OS_ERROR_LEVELS; i++){ if(code & (1<<i)){ if(!returned){ core->pushValue(core->error_handlers[i]); returned = true; } core->error_handlers[i] = func; } } } if(!returned){ pushNull(); } remove(-2); } void OS::setFuncs(const FuncDef * list, bool anonymous_setter_enabled, bool named_setter_enabled, int closure_values, void * user_param) { for(; list->func; list++){ pushStackValue(-1); pushString(list->name); // push closure_values for cfunction for(int i = 0; i < closure_values; i++){ pushStackValue(-2-closure_values); } pushCFunction(list->func, closure_values, user_param); setProperty(anonymous_setter_enabled, named_setter_enabled); } } void OS::setNumbers(const NumberDef * list, bool anonymous_setter_enabled, bool named_setter_enabled) { for(; list->name; list++){ pushStackValue(-1); pushString(list->name); pushNumber(list->value); setProperty(anonymous_setter_enabled, named_setter_enabled); } } void OS::setStrings(const StringDef * list, bool anonymous_setter_enabled, bool named_setter_enabled) { for(; list->name; list++){ pushStackValue(-1); pushString(list->name); pushString(list->value); setProperty(anonymous_setter_enabled, named_setter_enabled); } } void OS::setNulls(const NullDef * list, bool anonymous_setter_enabled, bool named_setter_enabled) { for(; list->name; list++){ pushStackValue(-1); pushString(list->name); pushNull(); setProperty(anonymous_setter_enabled, named_setter_enabled); } } void OS::getObject(const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { pushStackValue(-1); // 2: copy parent object pushString(name); // 3: index getProperty(anonymous_getter_enabled, named_getter_enabled, prototype_enabled); // 2: value if(isObject()){ remove(-2); // 1: remove parent object return; } pop(); // 1: parent object newObject(); // 2: result object pushStackValue(-2); // 3: copy parent object pushString(name); // 4: index pushStackValue(-3); // 5: copy result object setProperty(anonymous_getter_enabled, named_getter_enabled); // 2: parent + result remove(-2); // 1: remove parent object } void OS::getGlobalObject(const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { pushGlobals(); getObject(name, anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::getModule(const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { getGlobalObject(name, anonymous_getter_enabled, named_getter_enabled, prototype_enabled); pushStackValue(-1); pushGlobals(); setPrototype(); } void OS::getGlobal(const OS_CHAR * name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { getGlobal(Core::String(this, name), anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::getGlobal(const Core::String& name, bool anonymous_getter_enabled, bool named_getter_enabled, bool prototype_enabled) { pushGlobals(); pushString(name); getProperty(anonymous_getter_enabled, named_getter_enabled, prototype_enabled); } void OS::setGlobal(const OS_CHAR * name, bool anonymous_setter_enabled, bool named_setter_enabled) { setGlobal(Core::String(this, name), anonymous_setter_enabled, named_setter_enabled); } void OS::setGlobal(const Core::String& name, bool anonymous_setter_enabled, bool named_setter_enabled) { if(core->stack_values.count >= 1){ Core::Value object = core->global_vars; Core::Value value = core->stack_values[core->stack_values.count - 1]; Core::Value index = core->pushStringValue(name); core->setPropertyValue(object, Core::PropertyIndex(index), value, anonymous_setter_enabled, named_setter_enabled); pop(2); } } void OS::initGlobalFunctions() { struct Lib { static int print(OS * os, int params, int, int, void*) { int params_offs = os->getAbsoluteOffs(-params); for(int i = 0; i < params; i++){ String str = os->toString(params_offs + i); os->printf("%s", str.toChar()); if(i+1 < params){ os->printf("\t"); } } if(params > 0){ os->printf("\n"); } return 0; } static int echo(OS * os, int params, int, int, void*) { int params_offs = os->getAbsoluteOffs(-params); for(int i = 0; i < params; i++){ String str = os->toString(params_offs + i); os->printf("%s", str.toChar()); } return 0; } static int concat(OS * os, int params, int, int, void*) { if(params < 1){ return 0; } OS::Core::StringBuffer buf(os); int params_offs = os->getAbsoluteOffs(-params); for(int i = 0; i < params; i++){ buf += os->toString(params_offs + i); } os->core->pushValue(buf.toGCStringValue()); return 1; } static int compileText(OS * os, int params, int, int need_ret_values, void*) { if(params < 1){ return 0; } os->compile(); return 1; } static int compileFile(OS * os, int params, int, int need_ret_values, void*) { if(params < 1){ return 0; } bool required = os->toBool(-params+1); os->compileFile(os->toString(-params), required); return 1; } static int resolvePath(OS * os, int params, int, int, void*) { String filename = os->resolvePath(os->toString(-1)); if(filename.getDataSize()){ os->pushString(filename); return 1; } return 0; } static int debugBackTrace(OS * os, int params, int, int, void*) { switch(params){ case 0: os->core->pushBackTrace(0, 10); break; case 1: os->core->pushBackTrace(os->toInt(-params), 10); break; default: os->core->pushBackTrace(os->toInt(-params), os->toInt(-params+1)); } return 1; } static int terminate(OS * os, int params, int, int, void*) { os->setTerminated(true, os->toInt(-params)); return 0; } static int setErrorHandler(OS * os, int params, int, int, void*) { switch(params){ default: return 0; case 1: os->setErrorHandler(); break; case 2: os->setErrorHandler(os->popInt()); break; } return 1; } static int triggerError(OS * os, int params, int, int, void*) { int code = os->toInt(-params, OS_E_ERROR); String message = os->toString(-params+1, OS_TEXT("unknown error")); os->triggerError(code, message); return 0; } }; FuncDef list[] = { {OS_TEXT("print"), Lib::print}, {OS_TEXT("echo"), Lib::echo}, {OS_TEXT("concat"), Lib::concat}, {OS_TEXT("compileText"), Lib::compileText}, {OS_TEXT("compileFile"), Lib::compileFile}, {OS_TEXT("resolvePath"), Lib::resolvePath}, {OS_TEXT("debugBackTrace"), Lib::debugBackTrace}, {OS_TEXT("terminate"), Lib::terminate}, {OS_TEXT("setErrorHandler"), Lib::setErrorHandler}, {OS_TEXT("triggerError"), Lib::triggerError}, {} }; NumberDef numbers[] = { {OS_TEXT("E_ERROR"), OS_E_ERROR}, {OS_TEXT("E_WARNING"), OS_E_WARNING}, {OS_TEXT("E_NOTICE"), OS_E_NOTICE}, {} }; pushGlobals(); setFuncs(list); setNumbers(numbers); pop(); } void OS::initObjectClass() { static intptr_t iterator_crc = (intptr_t)&iterator_crc; static intptr_t array_iterator_crc = (intptr_t)&array_iterator_crc; struct Object { static int rawget(OS * os, int params, int, int, void*) { bool anonymous_getter_enabled = false, named_getter_enabled = false, prototype_enabled = false; switch(params){ case 0: break; default: os->pop(params-4); // no break case 4: prototype_enabled = os->popBool(false); // no break case 3: named_getter_enabled = os->popBool(false); // no break case 2: anonymous_getter_enabled = os->popBool(false); // no break case 1: os->getProperty(anonymous_getter_enabled, named_getter_enabled, prototype_enabled); return 1; } return 0; } static int rawset(OS * os, int params, int, int, void*) { bool anonymous_getter_enabled = false, named_getter_enabled = false; switch(params){ case 0: break; default: os->pop(params-4); // no break case 4: named_getter_enabled = os->popBool(false); // no break case 3: anonymous_getter_enabled = os->popBool(false); // no break case 2: os->setProperty(anonymous_getter_enabled, named_getter_enabled); } return 0; } static int getValueId(OS * os, int params, int, int, void*) { os->pushNumber(os->getValueId(-params-1)); return 1; } static int iteratorStep(OS * os, int params, int closure_values, int, void*) { OS_ASSERT(closure_values == 2); Core::Value self_var = os->core->getStackValue(-closure_values + 0); void * p = os->toUserdata(iterator_crc, -closure_values + 1); Core::Table::IteratorState * iter = (Core::Table::IteratorState*)p; if(iter->table){ Core::GCValue * self = self_var.getGCValue(); OS_ASSERT(self && iter->table == self->table); if(iter->prop){ os->pushBool(true); os->core->pushValue(iter->prop->index); os->core->pushValue(iter->prop->value); iter->prop = iter->ascending ? iter->prop->next : iter->prop->prev; return 3; } iter->table->removeIterator(iter); } return 0; } static void iteratorStateDestructor(OS * os, void * data, void * user_param) { Core::Table::IteratorState * iter = (Core::Table::IteratorState*)data; if(iter->table){ iter->table->removeIterator(iter); } } static int arrayIteratorStep(OS * os, int params, int closure_values, int, void*) { OS_ASSERT(closure_values == 2); Core::Value self_var = os->core->getStackValue(-closure_values + 0); int * pi = (int*)os->toUserdata(array_iterator_crc, -closure_values + 1); OS_ASSERT(self_var.type == OS_VALUE_TYPE_ARRAY && pi && pi[1]); if(pi[0] >= 0 && pi[0] < self_var.v.arr->values.count){ os->pushBool(true); os->pushNumber(pi[0]); os->core->pushValue(self_var.v.arr->values[pi[0]]); pi[0] += pi[1]; return 3; } return 0; } static int iterator(OS * os, int params, bool ascending) { Core::Value self_var = os->core->getStackValue(-params-1); if(self_var.type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); os->core->pushValue(self_var); int * pi = (int*)os->pushUserdata(array_iterator_crc, sizeof(int)*2); OS_ASSERT(pi); pi[0] = ascending ? 0 : self_var.v.arr->values.count-1; pi[1] = ascending ? 1 : -1; os->pushCFunction(arrayIteratorStep, 2); return 1; } Core::GCValue * self = self_var.getGCValue(); if(self && self->table && self->table->count > 0){ typedef Core::Table::IteratorState IteratorState; os->core->pushValue(self); IteratorState * iter = (IteratorState*)os->pushUserdata(iterator_crc, sizeof(IteratorState), iteratorStateDestructor); iter->table = NULL; iter->next = NULL; iter->prop = NULL; iter->ascending = ascending; self->table->addIterator(iter); os->pushCFunction(iteratorStep, 2); return 1; } return 0; } static int iterator(OS * os, int params, int closure_values, int, void*) { return iterator(os, params + closure_values, true); } static int reverseIterator(OS * os, int params, int closure_values, int, void*) { return iterator(os, params + closure_values, false); } static int smartSort(OS * os, int params, int(*arrcomp)(OS*, const void*, const void*, void*), int(*objcomp)(OS*, const void*, const void*, void*), void * user_param = NULL) { Core::Value self_var = os->core->getStackValue(-params-1); if(self_var.type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); if(arrcomp){ os->core->sortArray(self_var.v.arr, arrcomp, user_param); } os->core->pushValue(self_var); return 1; } Core::GCValue * self = self_var.getGCValue(); if(self){ if(self->table && objcomp){ os->core->sortTable(self->table, objcomp, user_param); } os->core->pushValue(self_var); return 1; } return 0; } static int sort(OS * os, int params, int, int, void*) { if(params < 1){ return smartSort(os, params, Core::compareArrayValues, Core::comparePropValues); } String prop_name(os); if(os->core->isValueString(os->core->getStackValue(-params), &prop_name)){ return smartSort(os, params, NULL, Core::compareObjectProperties, &prop_name); } return smartSort(os, params, Core::compareUserArrayValues, Core::compareUserPropValues); } static int rsort(OS * os, int params, int, int, void*) { if(params < 1){ return smartSort(os, params, Core::compareArrayValuesReverse, Core::comparePropValuesReverse); } String prop_name(os); if(os->core->isValueString(os->core->getStackValue(-params), &prop_name)){ return smartSort(os, params, NULL, Core::compareObjectPropertiesReverse, &prop_name); } return smartSort(os, params, Core::compareUserArrayValuesReverse, Core::compareUserPropValuesReverse); } static void userSortArrayByKeys(OS * os, Core::GCArrayValue * arr, int params, bool reverse) { Core::GCArrayValue * keys = os->core->pushArrayValue(); os->vectorReserveCapacity(keys->values, arr->values.count OS_DBG_FILEPOS); keys->values.count = arr->values.count; for(int i = 0; i < arr->values.count; i++){ keys->values[i] = i; } if(reverse){ os->core->sortArray(keys, Core::compareUserArrayValuesReverse); }else{ os->core->sortArray(keys, Core::compareUserArrayValues); } Vector<Core::Value> values; os->vectorReserveCapacity(values, arr->values.count OS_DBG_FILEPOS); OS_MEMCPY(values.buf, arr->values.buf, sizeof(Core::Value) * arr->values.count); values.count = arr->values.count; for(int i = 0; i < arr->values.count; i++){ arr->values[i] = values[(int)os->core->valueToInt(keys->values[i])]; } os->vectorClear(values); os->vectorClear(keys->values); os->pop(); } static int ksort(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); if(self_var.type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); if(params > 0){ userSortArrayByKeys(os, self_var.v.arr, params, false); }else{ // os->core->sortArray(self_var.v.arr, arrcomp); // array is always sorted by keys so it's nothing to do } os->core->pushValue(self_var); return 1; } Core::GCValue * self = self_var.getGCValue(); if(self){ if(self->table){ if(params > 0){ os->core->sortTable(self->table, Core::compareUserPropKeys); }else{ os->core->sortTable(self->table, Core::comparePropKeys); } } os->core->pushValue(self_var); return 1; } return 0; } static int krsort(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); if(self_var.type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); if(params > 0){ userSortArrayByKeys(os, self_var.v.arr, params, true); }else{ int mid = self_var.v.arr->values.count/2; for(int i = 0, j = self_var.v.arr->values.count-1; i < mid; i++, j--){ Core::Value tmp = self_var.v.arr->values[i]; self_var.v.arr->values[i] = self_var.v.arr->values[j]; self_var.v.arr->values[j] = tmp; } } os->core->pushValue(self_var); return 1; } Core::GCValue * self = self_var.getGCValue(); if(self){ if(self->table){ if(params > 0){ os->core->sortTable(self->table, Core::compareUserPropKeysReverse); }else{ os->core->sortTable(self->table, Core::comparePropKeysReverse); } } os->core->pushValue(self_var); return 1; } return 0; } static int length(OS * os, int params, int closure_values, int, void*) { Core::Value self_var = os->core->getStackValue(-params-closure_values-1); if(self_var.type == OS_VALUE_TYPE_ARRAY){ OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); os->pushNumber(self_var.v.arr->values.count); return 1; } Core::GCValue * self = self_var.getGCValue(); if(self){ os->pushNumber(self->table ? self->table->count : 0); return 1; } return 0; } static void appendQuotedString(Core::StringBuffer& buf, const Core::String& string) { buf += OS_TEXT("\""); int len = string.getLen(); const OS_CHAR * str = string.toChar(); for(int i = 0; i < len; i++, str++){ switch(*str){ case OS_TEXT('\"'): buf += OS_TEXT("\\\""); continue; case OS_TEXT('\r'): buf += OS_TEXT("\\r"); continue; case OS_TEXT('\n'): buf += OS_TEXT("\\n"); continue; case OS_TEXT('\t'): buf += OS_TEXT("\\t"); continue; case OS_TEXT('\\'): buf += OS_TEXT("\\\\"); continue; } if(*str < OS_TEXT(' ')){ buf += OS_TEXT("0x"); buf.append((OS_CHAR)'A' + ((int)*str >> 4)); buf.append((OS_CHAR)'A' + ((int)*str >> 0)); continue; } buf.append(*str); } buf += OS_TEXT("\""); } static int valueof(OS * os, int params, int closure_values, int, void*) { Core::Value self_var = os->core->getStackValue(-params-closure_values-1); switch(self_var.type){ case OS_VALUE_TYPE_NULL: os->pushString(os->core->strings->typeof_null); return 1; case OS_VALUE_TYPE_BOOL: os->pushString(self_var.v.boolean ? os->core->strings->syntax_true : os->core->strings->syntax_false); return 1; case OS_VALUE_TYPE_NUMBER: case OS_VALUE_TYPE_STRING: os->core->pushValue(self_var); return 1; } Core::GCValue * self = self_var.getGCValue(); if(!self){ return 0; } switch(self->type){ case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: { Core::StringBuffer str(os); str += OS_TEXT("<"); str += os->core->strings->typeof_userdata; str += OS_TEXT(":"); str += Core::String(os, (OS_INT)self->value_id); str += OS_TEXT(">"); os->pushString(str); return 1; } case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: { Core::StringBuffer str(os); str += OS_TEXT("<"); str += os->core->strings->typeof_function; str += OS_TEXT(":"); str += Core::String(os, (OS_INT)self->value_id); str += OS_TEXT(">"); os->pushString(str); return 1; } case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self)); Core::GCArrayValue * arr = (Core::GCArrayValue*)self; Core::StringBuffer buf(os); buf += OS_TEXT("["); Core::Value temp; for(int i = 0; i < arr->values.count; i++){ if(i > 0){ buf += OS_TEXT(","); } Core::Value value = arr->values[i]; if(os->core->getPropertyValue(temp, os->core->check_recursion, value, false)){ buf += OS_TEXT("<<RECURSION>>"); continue; } Core::GCValue * gcvalue = value.getGCValue(); if(gcvalue && gcvalue->table && gcvalue->table->count){ os->core->setPropertyValue(os->core->check_recursion, value, Core::Value(true), false, false); } Core::String value_str = os->core->valueToString(value, true); if(value.type == OS_VALUE_TYPE_STRING){ appendQuotedString(buf, value_str); }else{ buf += value_str; } } buf += OS_TEXT("]"); os->pushString(buf); return 1; } case OS_VALUE_TYPE_OBJECT: if(!self->table || !self->table->count){ os->pushString(OS_TEXT("{}")); return 1; } { Core::StringBuffer buf(os); buf += OS_TEXT("{"); int need_index = 0; Core::Property * prop = self->table->first; Core::Value temp; for(int i = 0; prop; prop = prop->next, i++){ if(i > 0){ buf += OS_TEXT(","); } if(prop->index.type == OS_VALUE_TYPE_NUMBER){ if(prop->index.v.number != (OS_FLOAT)need_index){ buf += String(os, prop->index.v.number, OS_AUTO_PRECISION); buf += OS_TEXT(":"); } need_index = (int)(prop->index.v.number + 1); }else if(prop->index.type == OS_VALUE_TYPE_STRING){ OS_ASSERT(!prop->index.v.string->table); appendQuotedString(buf, os->core->valueToString(prop->index)); buf += OS_TEXT(":"); }else{ Core::GCValue * gcvalue = prop->index.getGCValue(); if(os->core->getPropertyValue(temp, os->core->check_recursion, prop->index, false)){ buf += OS_TEXT("<<RECURSION>>"); }else{ if(gcvalue && gcvalue->table && gcvalue->table->count){ os->core->setPropertyValue(os->core->check_recursion, prop->index, Core::Value(true), false, false); } buf += os->core->valueToString(prop->index, true); } buf += OS_TEXT(":"); } if(os->core->getPropertyValue(temp, os->core->check_recursion, prop->value, false)){ buf += OS_TEXT("<<RECURSION>>"); continue; } Core::GCValue * gcvalue = prop->value.getGCValue(); if(gcvalue && gcvalue->table && gcvalue->table->count){ os->core->setPropertyValue(os->core->check_recursion, prop->value, Core::Value(true), false, false); } Core::String value_str = os->core->valueToString(prop->value, true); if(prop->value.type == OS_VALUE_TYPE_STRING){ appendQuotedString(buf, value_str); }else{ buf += value_str; } } os->pushString(buf += OS_TEXT("}")); return 1; } } return 0; } static int push(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); Core::Value value = os->core->getStackValue(-params); OS_INT num_index = 0; switch(self_var.type){ case OS_VALUE_TYPE_ARRAY: OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); os->vectorAddItem(self_var.v.arr->values, value OS_DBG_FILEPOS); // os->pushNumber(self_var.v.arr->values.count); os->core->pushValue(value); return 1; case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: num_index = self_var.v.object->table ? self_var.v.object->table->next_index : 0; break; default: return 0; } os->core->setPropertyValue(self_var, Core::PropertyIndex(num_index), value, false, false); // os->pushNumber(self_var.v.object->table->count); os->core->pushValue(value); return 1; } static int pop(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); switch(self_var.type){ case OS_VALUE_TYPE_ARRAY: OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); if(self_var.v.arr->values.count > 0){ os->core->pushValue(self_var.v.arr->values.lastElement()); os->vectorRemoveAtIndex(self_var.v.arr->values, self_var.v.arr->values.count-1); return 1; } return 0; case OS_VALUE_TYPE_OBJECT: case OS_VALUE_TYPE_USERDATA: // case OS_VALUE_TYPE_USERPTR: case OS_VALUE_TYPE_FUNCTION: case OS_VALUE_TYPE_CFUNCTION: if(self_var.v.object->table && self_var.v.object->table->count > 0){ os->core->pushValue(self_var.v.object->table->last->value); Core::PropertyIndex index = *self_var.v.object->table->last; os->core->deleteValueProperty(self_var.v.object, index, false, false, false); return 1; } break; } return 0; } static int hasOwnProperty(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); Core::Value index = os->core->getStackValue(-params); Core::GCValue * self = self_var.getGCValue(); if(self){ os->pushBool( os->core->hasProperty(self, index, true, true, false) ); return 1; } return 0; } static int hasProperty(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); Core::Value index = os->core->getStackValue(-params); Core::GCValue * self = self_var.getGCValue(); if(self){ os->pushBool( os->core->hasProperty(self, index, true, true, true) ); return 1; } return 0; } static int sub(OS * os, int params, int, int, void*) { int start, len, size; Core::Value self_var = os->core->getStackValue(-params-1); switch(self_var.type){ case OS_VALUE_TYPE_OBJECT: OS_ASSERT(dynamic_cast<Core::GCObjectValue*>(self_var.v.object)); size = self_var.v.object->table ? self_var.v.object->table->count : 0; break; default: return 0; } switch(params){ case 0: os->core->pushValue(self_var); return 1; case 1: start = os->toInt(-params); len = size; break; default: start = os->toInt(-params); len = os->toInt(-params+1); } if(start < 0){ start = size + start; if(start < 0){ start = 0; } } if(start >= size){ os->newObject(); return 1; } if(len < 0){ len = size - start + len; } if(len <= 0){ os->newObject(); return 1; } if(start + len > size){ len = size - start; } if(!start && len == size){ os->core->pushValue(self_var); return 1; } OS_ASSERT(self_var.v.object->table && self_var.v.object->table->first); Core::GCObjectValue * object = os->core->pushObjectValue(self_var.v.object->prototype); Core::Property * prop = self_var.v.object->table->first; int i = 0; for(; i < start; i++){ prop = prop->next; OS_ASSERT(prop); } Vector<Core::Value> captured_items; os->vectorReserveCapacity(captured_items, len*2 OS_DBG_FILEPOS); for(i = 0; i < len; i++, prop = prop->next){ OS_ASSERT(prop); os->vectorAddItem(captured_items, prop->index OS_DBG_FILEPOS); os->vectorAddItem(captured_items, prop->value OS_DBG_FILEPOS); } for(i = 0; i < len; i++){ os->core->setPropertyValue(object, captured_items[i*2], captured_items[i*2+1], false, false); } os->vectorClear(captured_items); return 1; } static int merge(OS * os, int params, int, int, void*) { if(params < 1) return 0; int offs = os->getAbsoluteOffs(-params); bool is_array = os->isArray(offs-1); if(is_array || os->isObject(offs-1)){ for(int i = 0; i < params; i++){ Core::Value value = os->core->getStackValue(offs+i); switch(value.type){ case OS_VALUE_TYPE_ARRAY: { OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(value.v.arr)); for(int j = 0; j < value.v.arr->values.count; j++){ os->pushStackValue(offs-1); os->core->pushValue(value.v.arr->values[j]); os->addProperty(); } break; } case OS_VALUE_TYPE_OBJECT: { OS_ASSERT(dynamic_cast<Core::GCObjectValue*>(value.v.object)); if(value.v.object->table){ Core::Property * prop = value.v.object->table->first; for(; prop; prop = prop->next){ os->pushStackValue(offs-1); if(is_array){ os->core->pushValue(prop->value); os->addProperty(); }else{ os->core->pushValue(prop->index); os->core->pushValue(prop->value); os->setProperty(); } } } break; } } } os->pushStackValue(offs-1); return 1; } return 0; } static int getKeys(OS * os, int params, int, int, void*) { Core::Value value = os->core->getStackValue(-params-1); switch(value.type){ case OS_VALUE_TYPE_ARRAY: { Core::GCArrayValue * arr = os->core->pushArrayValue(value.v.arr->values.count); for(int i = 0; i < value.v.arr->values.count; i++){ os->vectorAddItem(arr->values, Core::Value(i) OS_DBG_FILEPOS); } return 1; } case OS_VALUE_TYPE_OBJECT: { if(value.v.object->table){ Core::GCArrayValue * arr = os->core->pushArrayValue(value.v.object->table->count); Core::Property * prop = value.v.object->table->first; for(int i = 0; prop; prop = prop->next, i++){ os->vectorAddItem(arr->values, prop->index OS_DBG_FILEPOS); } }else{ os->newArray(); } return 1; } } return 0; } static int getValues(OS * os, int params, int, int, void*) { Core::Value value = os->core->getStackValue(-params-1); switch(value.type){ case OS_VALUE_TYPE_ARRAY: os->core->pushValue(value); return 1; case OS_VALUE_TYPE_OBJECT: { if(value.v.object->table){ Core::GCArrayValue * arr = os->core->pushArrayValue(value.v.object->table->count); Core::Property * prop = value.v.object->table->first; for(int i = 0; prop; prop = prop->next, i++){ os->vectorAddItem(arr->values, prop->value OS_DBG_FILEPOS); } }else{ os->newArray(); } return 1; } } return 0; } }; FuncDef list[] = { {OS_TEXT("rawget"), Object::rawget}, {OS_TEXT("rawset"), Object::rawset}, {OS_TEXT("__get@osValueId"), Object::getValueId}, {core->strings->__len, Object::length}, // {OS_TEXT("__get@length"), Object::length}, {core->strings->__iter, Object::iterator}, {OS_TEXT("reverseIter"), Object::reverseIterator}, {core->strings->__valueof, Object::valueof}, {OS_TEXT("sort"), Object::sort}, {OS_TEXT("rsort"), Object::rsort}, {OS_TEXT("ksort"), Object::ksort}, {OS_TEXT("krsort"), Object::krsort}, {OS_TEXT("push"), Object::push}, {OS_TEXT("pop"), Object::pop}, {OS_TEXT("hasOwnProperty"), Object::hasOwnProperty}, {OS_TEXT("hasProperty"), Object::hasProperty}, {OS_TEXT("merge"), Object::merge}, {OS_TEXT("getKeys"), Object::getKeys}, {OS_TEXT("getValues"), Object::getValues}, {OS_TEXT("__get@keys"), Object::getKeys}, {OS_TEXT("__get@values"), Object::getValues}, {} }; core->pushValue(core->prototypes[Core::PROTOTYPE_OBJECT]); setFuncs(list); pop(); } void OS::initArrayClass() { struct Array { static int sub(OS * os, int params, int, int, void*) { int start, len, size; Core::Value self_var = os->core->getStackValue(-params-1); switch(self_var.type){ case OS_VALUE_TYPE_ARRAY: OS_ASSERT(dynamic_cast<Core::GCArrayValue*>(self_var.v.arr)); size = self_var.v.arr->values.count; break; default: return 0; } switch(params){ case 0: os->core->pushValue(self_var); return 1; case 1: start = os->toInt(-params); len = size; break; default: start = os->toInt(-params); len = os->toInt(-params+1); } if(start < 0){ start = size + start; if(start < 0){ start = 0; } } if(start >= size){ os->newArray(); return 1; } if(len < 0){ len = size - start + len; } if(len <= 0){ os->newArray(); return 1; } if(start + len > size){ len = size - start; } if(!start && len == size){ os->core->pushValue(self_var); return 1; } Core::GCArrayValue * arr = os->core->pushArrayValue(len); for(int i = 0; i < len; i++){ os->vectorAddItem(arr->values, self_var.v.arr->values[start+i] OS_DBG_FILEPOS); } return 1; } }; FuncDef list[] = { {OS_TEXT("sub"), Array::sub}, {} }; core->pushValue(core->prototypes[Core::PROTOTYPE_ARRAY]); setFuncs(list); pop(); } void OS::initStringClass() { struct String { static int length(OS * os, int params, int, int, void*) { Core::Value self_var = os->core->getStackValue(-params-1); Core::GCValue * self = self_var.getGCValue(); if(self){ if(self->type == OS_VALUE_TYPE_STRING){ Core::GCStringValue * string = (Core::GCStringValue*)self; os->pushNumber(string->getLen()); // os->pushNumber(os->core->valueToString(self).getDataSize() / sizeof(OS_CHAR)); return 1; } os->core->pushOpResultValue(Core::Program::OP_LENGTH, self_var); return 1; } return 0; } static int sub(OS * os, int params, int, int, void*) { int start, len; OS::String str = os->toString(-params-1); int size = str.getLen(); switch(params){ case 0: os->pushStackValue(-params-1); return 1; case 1: start = os->toInt(-params); len = size; break; default: start = os->toInt(-params); len = os->toInt(-params+1); } if(start < 0){ start = size + start; if(start < 0){ start = 0; } } if(start >= size){ os->pushString(OS_TEXT("")); return 1; } if(len < 0){ len = size - start + len; } if(len <= 0){ os->pushString(OS_TEXT("")); return 1; } if(start + len > size){ len = size - start; } if(!start && len == size){ os->pushStackValue(-params-1); return 1; } os->pushString(str.toChar() + start, len); return 1; } }; FuncDef list[] = { {core->strings->__len, String::length}, {OS_TEXT("sub"), String::sub}, // {OS_TEXT("__get@length"), String::length}, {} }; core->pushValue(core->prototypes[Core::PROTOTYPE_STRING]); setFuncs(list); pop(); } void OS::initFunctionClass() { struct Function { static int apply(OS * os, int params, int, int need_ret_values, void*) { int offs = os->getAbsoluteOffs(-params); os->pushStackValue(offs-1); // self as func if(params < 1){ os->pushNull(); return os->call(0, need_ret_values); } os->pushStackValue(offs); // first param - new this Core::Value array_var = os->core->getStackValue(offs+1); if(array_var.type == OS_VALUE_TYPE_ARRAY){ int count = array_var.v.arr->values.count; for(int i = 0; i < count; i++){ os->core->pushValue(array_var.v.arr->values[i]); } return os->call(count, need_ret_values); } return os->call(0, need_ret_values); } static int call(OS * os, int params, int, int need_ret_values, void*) { #if 1 return os->call(params-1, need_ret_values); #else int offs = os->getAbsoluteOffs(-params); os->pushStackValue(offs-1); // self as func if(params < 1){ os->pushNull(); // this return os->call(0, need_ret_values); } os->pushStackValue(offs); // first param - new this for(int i = 1; i < params; i++){ os->pushStackValue(offs + i); } return os->call(params-1, need_ret_values); #endif } static int applyEnv(OS * os, int params, int, int need_ret_values, void *) { Core::Value save_env; Core::Value func = os->core->getStackValue(-params-1); if(func.type == OS_VALUE_TYPE_FUNCTION){ save_env = func.v.func->env; func.v.func->env = os->core->getStackValue(-params).getGCValue(); } os->remove(-params); int r = apply(os, params-1, 0, need_ret_values, NULL); if(func.type == OS_VALUE_TYPE_FUNCTION){ func.v.func->env = save_env; } return r; } static int callEnv(OS * os, int params, int, int need_ret_values, void *) { Core::Value save_env; Core::Value func = os->core->getStackValue(-params-1); if(func.type == OS_VALUE_TYPE_FUNCTION){ save_env = func.v.func->env; func.v.func->env = os->core->getStackValue(-params).getGCValue(); } os->remove(-params); int r = call(os, params-1, 0, need_ret_values, NULL); if(func.type == OS_VALUE_TYPE_FUNCTION){ func.v.func->env = save_env; } return r; } static int getEnv(OS * os, int params, int, int, void*) { Core::Value func = os->core->getStackValue(-params-1); if(func.type == OS_VALUE_TYPE_FUNCTION){ os->core->pushValue(func.v.func->env); return 1; } return 0; } static int setEnv(OS * os, int params, int, int, void*) { Core::Value func = os->core->getStackValue(-params-1); if(func.type == OS_VALUE_TYPE_FUNCTION){ Core::Value env = os->core->getStackValue(-params); func.v.func->env = env.getGCValue(); } return 0; } static int iterator(OS * os, int params, int, int need_ret_values, void*) { os->pushStackValue(-params-1); // self as func return 1; } }; FuncDef list[] = { {OS_TEXT("apply"), Function::apply}, {OS_TEXT("applyEnv"), Function::applyEnv}, {OS_TEXT("call"), Function::call}, {OS_TEXT("callEnv"), Function::callEnv}, {OS_TEXT("__get@") OS_ENV_VAR_NAME, Function::getEnv}, {OS_TEXT("__set@") OS_ENV_VAR_NAME, Function::setEnv}, {core->strings->__iter, Function::iterator}, {} }; core->pushValue(core->prototypes[Core::PROTOTYPE_FUNCTION]); setFuncs(list); pop(); } /* The following functions are based on a C++ class MTRand by Richard J. Wagner. For more information see the web page at http://www-personal.engin.umich.edu/~wagnerr/MersenneTwister.html It's port from PHP framework. */ #define OS_RAND_N RAND_STATE_SIZE /* length of state vector */ #define OS_RAND_M (397) /* a period parameter */ #define OS_RAND_hiBit(u) ((u) & 0x80000000U) /* mask all but highest bit of u */ #define OS_RAND_loBit(u) ((u) & 0x00000001U) /* mask all but lowest bit of u */ #define OS_RAND_loBits(u) ((u) & 0x7FFFFFFFU) /* mask the highest bit of u */ #define OS_RAND_mixBits(u, v) (OS_RAND_hiBit(u)|OS_RAND_loBits(v)) /* move hi bit of u to hi bit of v */ #define OS_RAND_twist(m,u,v) (m ^ (OS_RAND_mixBits(u,v)>>1) ^ ((OS_U32)(-(OS_INT32)(OS_RAND_loBit(u))) & 0x9908b0dfU)) #define OS_RAND_MAX 0x7FFFFFFF /* (1<<31) - 1 */ #define OS_RAND_RANGE(__n, __min, __max, __tmax) \ (__n) = (__min) + (long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0))) #if defined _MSC_VER && !defined IW_SDK #include <windows.h> #define OS_RAND_GENERATE_SEED() (((long) (time(0) * GetCurrentProcessId())) ^ ((long) (1000000.0))) // #elif !defined IW_SDK // #define OS_RAND_GENERATE_SEED() (((long) (time(0) * getpid())) ^ ((long) (1000000.0))) #else #define OS_RAND_GENERATE_SEED() (((long) (time(0))) ^ ((long) (1000000.0))) #endif void OS::Core::randInitialize(OS_U32 seed) { rand_seed = seed; OS_U32 * s = rand_state; OS_U32 * r = s; *s++ = seed & 0xffffffffU; for(int i = 1; i < OS_RAND_N; ++i ) { *s++ = ( 1812433253U * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffU; r++; } randReload(); } void OS::Core::randReload() { /* Generate N new values in state Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) */ OS_U32 * state = rand_state; OS_U32 * p = state; int i; for(i = OS_RAND_N - OS_RAND_M; i--; ++p){ *p = OS_RAND_twist(p[OS_RAND_M], p[0], p[1]); } for(i = OS_RAND_M; --i; ++p){ *p = OS_RAND_twist(p[OS_RAND_M-OS_RAND_N], p[0], p[1]); } *p = OS_RAND_twist(p[OS_RAND_M-OS_RAND_N], p[0], state[0]); rand_left = OS_RAND_N; rand_next = state; } double OS::Core::getRand() { /* Pull a 32-bit integer from the generator state Every other access function simply transforms the numbers extracted here */ if(!rand_left){ if(!rand_next){ randInitialize(OS_RAND_GENERATE_SEED()); }else{ randReload(); } } --rand_left; OS_U32 s1 = *rand_next++; s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9d2c5680U; s1 ^= (s1 << 15) & 0xefc60000U; return (double)((s1 ^ (s1 >> 18))>>1) / (double)OS_RAND_MAX; } double OS::Core::getRand(double up) { return ::floor(getRand()*(up-1) + 0.5f); } double OS::Core::getRand(double min, double max) { return getRand() * (max - min) + min; } #define OS_MATH_PI ((OS_NUMBER)3.1415926535897932384626433832795) #define OS_RADIANS_PER_DEGREE (OS_MATH_PI/180.0f) void OS::initMathModule() { struct Math { static int minmax(OS * os, int params, OS_EOpcode opcode) { OS_ASSERT(params >= 0); if(params <= 1){ return params; } int params_offs = os->getAbsoluteOffs(-params); os->pushStackValue(params_offs); // save temp result for(int i = 1; i < params; i++){ os->pushStackValue(-1); // copy temp result os->pushStackValue(params_offs + i); os->runOp(opcode); // remove params & push op result if(!os->toBool()){ os->pop(2); // remove op result and temp result os->pushStackValue(params_offs + i); // save temp result continue; } os->pop(); } return 1; } static int min_func(OS * os, int params, int, int, void*) { return minmax(os, params, OP_LOGIC_LE); } static int max_func(OS * os, int params, int, int, void*) { return minmax(os, params, OP_LOGIC_GE); } static int abs(OS * os, int params, int, int, void*) { os->pushNumber(::fabs(os->toNumber(-params))); return 1; } static int ceil(OS * os, int params, int, int, void*) { os->pushNumber(::ceil(os->toNumber(-params))); return 1; } static int floor(OS * os, int params, int, int, void*) { os->pushNumber(::floor(os->toNumber(-params))); return 1; } static int round(OS * os, int params, int, int, void*) { double a = (double)os->toNumber(-params); if(params >= 2){ int precision = (int)os->toNumber(-params+1); if(precision <= 0){ if(precision < 0){ double p = 10.0f; for(int i = -precision-1; i > 0; i--){ p *= 10.0f; } os->pushNumber(::floor(a / p + 0.5f) * p); return 1; } os->pushNumber(::floor(a + 0.5f)); return 1; } double p = 10.0f; for(int i = precision-1; i > 0; i--){ p *= 10.0f; } os->pushNumber(::floor(a * p + 0.5f) / p); return 1; } os->pushNumber(::floor(a + 0.5f)); return 1; } static int sin(OS * os, int params, int, int, void*) { os->pushNumber(::sin(os->toNumber(-params))); return 1; } static int sinh(OS * os, int params, int, int, void*) { os->pushNumber(::sinh(os->toNumber(-params))); return 1; } static int cos(OS * os, int params, int, int, void*) { os->pushNumber(::cos(os->toNumber(-params))); return 1; } static int cosh(OS * os, int params, int, int, void*) { os->pushNumber(::cosh(os->toNumber(-params))); return 1; } static int tan(OS * os, int params, int, int, void*) { os->pushNumber(::tan(os->toNumber(-params))); return 1; } static int tanh(OS * os, int params, int, int, void*) { os->pushNumber(::tanh(os->toNumber(-params))); return 1; } static int acos(OS * os, int params, int, int, void*) { os->pushNumber(::acos(os->toNumber(-params))); return 1; } static int asin(OS * os, int params, int, int, void*) { os->pushNumber(::asin(os->toNumber(-params))); return 1; } static int atan(OS * os, int params, int, int, void*) { os->pushNumber(::atan(os->toNumber(-params))); return 1; } static int atan2(OS * os, int params, int, int, void*) { os->pushNumber(::atan2(os->toNumber(-params), os->toNumber(-params+1))); return 1; } static int exp(OS * os, int params, int, int, void*) { os->pushNumber(::exp(os->toNumber(-params))); return 1; } static int frexp(OS * os, int params, int, int, void*) { int e; os->pushNumber(::frexp(os->toNumber(-params), &e)); os->pushNumber(e); return 2; } static int ldexp(OS * os, int params, int, int, void*) { os->pushNumber(::ldexp(os->toNumber(-params), (int)os->toNumber(-params+1))); return 1; } static int pow(OS * os, int params, int, int, void*) { os->pushNumber(::pow(os->toNumber(-params), os->toNumber(-params+1))); return 1; } static int random(OS * os, int params, int, int, void*) { OS::Core * core = os->core; switch(params){ case 0: os->pushNumber(core->getRand()); return 1; case 1: os->pushNumber(core->getRand(os->toNumber(-params))); return 1; case 2: os->pushNumber(core->getRand(os->toNumber(-params), os->toNumber(-params+1))); return 1; } return 0; } static int getrandseed(OS * os, int params, int, int, void*) { os->pushNumber((OS_NUMBER)os->core->rand_seed); return 1; } static int setrandseed(OS * os, int params, int, int, void*) { os->core->rand_seed = (OS_U32)os->toNumber(-params); return 0; } static int fmod(OS * os, int params, int, int, void*) { os->pushNumber(::fmod(os->toNumber(-params), os->toNumber(-params+1))); return 1; } static int modf(OS * os, int params, int, int, void*) { double ip; double fp = ::modf(os->toNumber(-params), &ip); os->pushNumber(ip); os->pushNumber(fp); return 2; } static int sqrt(OS * os, int params, int, int, void*) { os->pushNumber(::sqrt(os->toNumber(-params))); return 1; } static int log(OS * os, int params, int, int, void*) { double x = os->toNumber(-params); OS_NUMBER base; if(os->isNumber(-params+1, &base)){ if(base == 10){ os->pushNumber(::log10(x)); }else{ os->pushNumber(::log(x)/::log(base)); } }else{ os->pushNumber(::log(x)); } return 1; } static int deg(OS * os, int params, int, int, void*) { os->pushNumber(os->toNumber(-params)/OS_RADIANS_PER_DEGREE); return 1; } static int rad(OS * os, int params, int, int, void*) { os->pushNumber(os->toNumber(-params)*OS_RADIANS_PER_DEGREE); return 1; } }; FuncDef list[] = { {OS_TEXT("min"), Math::min_func}, {OS_TEXT("max"), Math::max_func}, {OS_TEXT("abs"), Math::abs}, {OS_TEXT("ceil"), Math::ceil}, {OS_TEXT("floor"), Math::floor}, {OS_TEXT("round"), Math::round}, {OS_TEXT("sin"), Math::sin}, {OS_TEXT("sinh"), Math::sinh}, {OS_TEXT("cos"), Math::cos}, {OS_TEXT("cosh"), Math::cosh}, {OS_TEXT("tan"), Math::tan}, {OS_TEXT("tanh"), Math::tanh}, {OS_TEXT("acos"), Math::acos}, {OS_TEXT("asin"), Math::asin}, {OS_TEXT("atan"), Math::atan}, {OS_TEXT("atan2"), Math::atan2}, {OS_TEXT("exp"), Math::exp}, {OS_TEXT("frexp"), Math::frexp}, {OS_TEXT("ldexp"), Math::ldexp}, {OS_TEXT("random"), Math::random}, {OS_TEXT("__get@randseed"), Math::getrandseed}, {OS_TEXT("__set@randseed"), Math::setrandseed}, {OS_TEXT("fmod"), Math::fmod}, {OS_TEXT("modf"), Math::modf}, {OS_TEXT("sqrt"), Math::sqrt}, {OS_TEXT("log"), Math::log}, {OS_TEXT("deg"), Math::deg}, {OS_TEXT("rad"), Math::rad}, {} }; NumberDef numbers[] = { {OS_TEXT("PI"), OS_MATH_PI}, {OS_TEXT("MAX_NUMBER"), OS_MAX_NUMBER}, {} }; getModule(OS_TEXT("math")); setFuncs(list); setNumbers(numbers); pop(); } void OS::initGCModule() { struct GC { static int getAllocatedBytes(OS * os, int params, int, int, void*) { os->pushNumber(os->getAllocatedBytes()); return 1; } static int getMaxAllocatedBytes(OS * os, int params, int, int, void*) { os->pushNumber(os->getMaxAllocatedBytes()); return 1; } static int getCachedBytes(OS * os, int params, int, int, void*) { os->pushNumber(os->getCachedBytes()); return 1; } static int getNumObjects(OS * os, int params, int, int, void*) { os->pushNumber(os->core->values.count); return 1; } static int getNumCreatedObjects(OS * os, int params, int, int, void*) { os->pushNumber(os->core->num_created_values); return 1; } static int getNumDestroyedObjects(OS * os, int params, int, int, void*) { os->pushNumber(os->core->num_destroyed_values); return 1; } }; FuncDef list[] = { {OS_TEXT("__get@allocatedBytes"), GC::getAllocatedBytes}, {OS_TEXT("__get@maxAllocatedBytes"), GC::getMaxAllocatedBytes}, {OS_TEXT("__get@cachedBytes"), GC::getCachedBytes}, {OS_TEXT("__get@numObjects"), GC::getNumObjects}, {OS_TEXT("__get@numCreatedObjects"), GC::getNumCreatedObjects}, {OS_TEXT("__get@numDestroyedObjects"), GC::getNumDestroyedObjects}, {} }; getModule(OS_TEXT("GC")); setFuncs(list); pop(); } void OS::initLangTokenizerModule() { struct LangTokenizer { enum { TOKEN_TYPE_STRING, TOKEN_TYPE_NUMBER, TOKEN_TYPE_NAME, TOKEN_TYPE_OPERATOR }; static int getTokenType(Core::TokenType type) { switch(type){ case Core::Tokenizer::NAME: return TOKEN_TYPE_NAME; case Core::Tokenizer::STRING: return TOKEN_TYPE_STRING; case Core::Tokenizer::NUMBER: return TOKEN_TYPE_NUMBER; } return TOKEN_TYPE_OPERATOR; } static void pushTokensAsObject(OS * os, Core::Tokenizer& tokenizer) { os->newArray(); int count = tokenizer.getNumTokens(); for(int i = 0; i < count; i++){ os->pushStackValue(-1); os->newObject(); { Core::TokenData * token = tokenizer.getToken(i); os->pushStackValue(-1); os->pushString(OS_TEXT("str")); os->pushString(token->str); os->setProperty(); #if 0 os->pushStackValue(-1); os->pushString(OS_TEXT("line")); os->pushNumber(token->line+1); os->setProperty(); os->pushStackValue(-1); os->pushString(OS_TEXT("pos")); os->pushNumber(token->pos+1); os->setProperty(); #endif os->pushStackValue(-1); os->pushString(OS_TEXT("type")); os->pushNumber(getTokenType(token->type)); os->setProperty(); } os->addProperty(); } } static int parseText(OS * os, int params, int, int, void*) { String str = os->toString(-params); if(str.getDataSize() == 0){ return 0; } Core::Tokenizer tokenizer(os); tokenizer.parseText(str.toChar(), str.getLen(), String(os)); pushTokensAsObject(os, tokenizer); return 1; } static int parseFile(OS * os, int params, int, int, void*) { String filename = os->resolvePath(os->toString(-params)); if(filename.getDataSize() == 0){ return 0; } Core::FileStreamReader file(os, filename); if(!file.f){ return 0; } Core::MemStreamWriter file_data(os); file_data.writeFromStream(&file); Core::Tokenizer tokenizer(os); tokenizer.parseText((OS_CHAR*)file_data.buffer.buf, file_data.buffer.count, filename); pushTokensAsObject(os, tokenizer); return 1; } }; FuncDef list[] = { {OS_TEXT("parseText"), LangTokenizer::parseText}, {OS_TEXT("parseFile"), LangTokenizer::parseFile}, {} }; NumberDef numbers[] = { {OS_TEXT("TOKEN_TYPE_STRING"), LangTokenizer::TOKEN_TYPE_STRING}, {OS_TEXT("TOKEN_TYPE_NUMBER"), LangTokenizer::TOKEN_TYPE_NUMBER}, {OS_TEXT("TOKEN_TYPE_NAME"), LangTokenizer::TOKEN_TYPE_NAME}, {OS_TEXT("TOKEN_TYPE_OPERATOR"), LangTokenizer::TOKEN_TYPE_OPERATOR}, {} }; getModule(OS_TEXT("LangTokenizer")); setFuncs(list); setNumbers(numbers); pop(); } #define OS_AUTO_TEXT(exp) OS_TEXT(#exp) void OS::initPreScript() { eval(OS_AUTO_TEXT( // it's ObjectScript code here Object.__get@length = function(){ return #this } modules_loaded = {} function require(filename, required){ filename = resolvePath(filename) return filename && (modules_loaded.rawget(filename) || function(){ modules_loaded[filename] = {} // block recursive require modules_loaded[filename] = compileFile(filename, required)() return modules_loaded[filename] }()) } )); } void OS::initPostScript() { eval(OS_AUTO_TEXT( // it's ObjectScript code here Object.__setempty = Object.push Object.__getempty = Object.pop )); } int OS::Core::syncRetValues(int need_ret_values, int cur_ret_values) { if(cur_ret_values > need_ret_values){ pop(cur_ret_values - need_ret_values); }else{ for(; cur_ret_values < need_ret_values; cur_ret_values++){ pushNull(); } } return need_ret_values; } OS::Core::GCObjectValue * OS::Core::initObjectInstance(GCObjectValue * object) { struct Lib { static GCObjectValue * initObjectInstance_r(Core * core, GCObjectValue * object, GCValue * prototype) { if(prototype->prototype){ initObjectInstance_r(core, object, prototype->prototype); } Value value; if(core->getPropertyValue(value, prototype, PropertyIndex(core->strings->__object, PropertyIndex::KeepStringIndex()), false)){ GCValue * object_props = value.getGCValue(); if(object_props->table){ Property * prop = object_props->table->first; for(; prop; prop = prop->next){ core->pushCloneValue(prop->value); core->setPropertyValue(object, *prop, core->stack_values.lastElement(), true, true); core->pop(); } } } return object; } }; if(object->prototype){ Lib::initObjectInstance_r(this, object, object->prototype); } return object; } void OS::Core::pushArguments(StackFunction * stack_func) { if(!stack_func->arguments){ int i; GCArrayValue * args = pushArrayValue(); Upvalues * func_upvalues = stack_func->locals; int num_params = stack_func->num_params - stack_func->num_extra_params; for(i = 0; i < num_params; i++){ allocator->vectorAddItem(args->values, func_upvalues->locals[i] OS_DBG_FILEPOS); } int num_locals = func_upvalues->num_locals; for(i = 0; i < stack_func->num_extra_params; i++){ allocator->vectorAddItem(args->values, func_upvalues->locals[i + num_locals] OS_DBG_FILEPOS); } stack_func->arguments = args; }else{ pushValue(stack_func->arguments); } } void OS::Core::pushArgumentsWithNames(StackFunction * stack_func) { int i; GCObjectValue * args = pushObjectValue(); Upvalues * func_upvalues = stack_func->locals; FunctionDecl * func_decl = stack_func->func->func_decl; int num_params = stack_func->num_params - stack_func->num_extra_params; for(i = 0; i < num_params; i++){ setPropertyValue(args, PropertyIndex(func_decl->locals[i].name.string, PropertyIndex::KeepStringIndex()), func_upvalues->locals[i], false, false); } int num_locals = func_upvalues->num_locals; if(num_params < func_decl->num_params){ for(; i < func_decl->num_params; i++){ setPropertyValue(args, PropertyIndex(func_decl->locals[i].name.string, PropertyIndex::KeepStringIndex()), Value(), false, false); } }else{ for(i = 0; i < stack_func->num_extra_params; i++){ setPropertyValue(args, Value(args->table ? args->table->next_index : 0), func_upvalues->locals[i + num_locals], false, false); } } } void OS::Core::pushRestArguments(StackFunction * stack_func) { if(!stack_func->rest_arguments){ GCArrayValue * args = pushArrayValue(); Upvalues * func_upvalues = stack_func->locals; int num_locals = func_upvalues->num_locals; for(int i = 0; i < stack_func->num_extra_params; i++){ allocator->vectorAddItem(args->values, func_upvalues->locals[i + num_locals] OS_DBG_FILEPOS); } stack_func->rest_arguments = args; }else{ pushValue(stack_func->rest_arguments); } } void OS::Core::pushBackTrace(int skip_funcs, int max_trace_funcs) { GCArrayValue * arr = pushArrayValue(); String function_str(allocator, OS_TEXT("function")); String name_str(allocator, OS_TEXT("name")); String file_str(allocator, OS_TEXT("file")); String line_str(allocator, OS_TEXT("line")); String pos_str(allocator, OS_TEXT("pos")); String token_str(allocator, OS_TEXT("token")); String object_str(allocator, OS_TEXT("object")); String arguments_str(allocator, OS_TEXT("arguments")); String core_str(allocator, OS_TEXT("<<CORE>>")); String lambda_str(allocator, OS_TEXT("<<lambda>>")); for(int i = call_stack_funcs.count-1-skip_funcs; i >= 0 && arr->values.count < max_trace_funcs; i--){ StackFunction * stack_func = call_stack_funcs.buf + i; Program * prog = stack_func->func->prog; if(!stack_func->func->name && !prog->filename.getDataSize()){ continue; } GCObjectValue * obj = pushObjectValue(); setPropertyValue(obj, PropertyIndex(name_str, PropertyIndex::KeepStringIndex()), stack_func->func->name ? stack_func->func->name : lambda_str.string, false, false); setPropertyValue(obj, PropertyIndex(function_str, PropertyIndex::KeepStringIndex()), stack_func->func, false, false); const String& filename = prog->filename.getDataSize() ? prog->filename : core_str; setPropertyValue(obj, PropertyIndex(file_str, PropertyIndex::KeepStringIndex()), filename.string, false, false); Program::DebugInfoItem * debug_info = NULL; if(prog->filename.getDataSize() && prog->debug_info.count > 0){ int opcode_pos = stack_func->opcodes.getPos() + stack_func->func->func_decl->opcodes_pos; debug_info = prog->getDebugInfo(opcode_pos); } setPropertyValue(obj, PropertyIndex(line_str, PropertyIndex::KeepStringIndex()), debug_info ? debug_info->line : Value(), false, false); setPropertyValue(obj, PropertyIndex(pos_str, PropertyIndex::KeepStringIndex()), debug_info ? debug_info->pos : Value(), false, false); setPropertyValue(obj, PropertyIndex(token_str, PropertyIndex::KeepStringIndex()), debug_info ? debug_info->token.string : Value(), false, false); setPropertyValue(obj, PropertyIndex(object_str, PropertyIndex::KeepStringIndex()), stack_func->self, false, false); pushArgumentsWithNames(stack_func); setPropertyValue(obj, PropertyIndex(arguments_str, PropertyIndex::KeepStringIndex()), stack_values.lastElement(), false, false); pop(); // remove args setPropertyValue(arr, Value(arr->values.count), obj, false, false); pop(); // remove obj } } int OS::Core::call(int params, int ret_values, GCValue * self_for_proto, bool allow_only_enter_func) { if(terminated){ error(OS_E_ERROR, OS_TEXT("ObjectScript is terminated, you could reset terminate state using OS::resetTerminated if necessary")); pop(params + 2); return syncRetValues(ret_values, 0); } if(stack_values.count >= 2+params){ int end_stack_size = stack_values.count-2-params; Value func_value = stack_values[stack_values.count-2-params]; switch(func_value.type){ case OS_VALUE_TYPE_FUNCTION: { Value self = stack_values[stack_values.count-1-params]; enterFunction(func_value.v.func, self, self_for_proto, params, 2, ret_values); if(allow_only_enter_func){ return 0; } ret_values = execute(); OS_ASSERT(stack_values.count == end_stack_size + ret_values); return ret_values; } case OS_VALUE_TYPE_CFUNCTION: { int stack_size_without_params = getStackOffs(-2-params); GCCFunctionValue * cfunc_value = func_value.v.cfunc; if(cfunc_value->num_closure_values > 0){ reserveStackValues(stack_values.count + cfunc_value->num_closure_values); Value * closure_values = (Value*)(cfunc_value + 1); OS_MEMCPY(stack_values.buf + stack_values.count, closure_values, sizeof(Value)*cfunc_value->num_closure_values); stack_values.count += cfunc_value->num_closure_values; } int func_ret_values = cfunc_value->func(allocator, params, cfunc_value->num_closure_values, ret_values, cfunc_value->user_param); #if 0 if(cfunc_value->num_closure_values > 0){ Value * closure_values = (Value*)(cfunc_value + 1); OS_MEMCPY(closure_values, stack_values.buf + stack_values.count, sizeof(Value)*cfunc_value->num_closure_values); } #endif int remove_values = getStackOffs(-func_ret_values) - stack_size_without_params; OS_ASSERT(remove_values >= 0); removeStackValues(stack_size_without_params, remove_values); ret_values = syncRetValues(ret_values, func_ret_values); OS_ASSERT(stack_values.count == end_stack_size + ret_values); return ret_values; } case OS_VALUE_TYPE_OBJECT: { GCValue * object = initObjectInstance(pushObjectValue(func_value.v.value)); object->is_object_instance = true; bool prototype_enabled = true; Value func; if(getPropertyValue(func, func_value, PropertyIndex(strings->__construct, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { pushValue(func); pushValue(object); moveStackValues(-3, 3, -3-params); call(params, 1); // 4 values in stack here object = stack_values.lastElement().getGCValue(); if(object){ stack_values.count -= 3; stack_values.lastElement() = object; return syncRetValues(ret_values, 1); }else{ pop(4); return syncRetValues(ret_values, 0); } } removeStackValues(-3, 2); return syncRetValues(ret_values, 1); } case OS_VALUE_TYPE_USERDATA: { bool prototype_enabled = true; Value func; if(getPropertyValue(func, func_value, PropertyIndex(strings->__construct, PropertyIndex::KeepStringIndex()), prototype_enabled) && func.isFunction()) { stack_values[stack_values.count-2-params] = func; stack_values[stack_values.count-1-params] = func_value; return call(params, ret_values); // request result } break; } } } // OS_ASSERT(false); pop(params + 2); return syncRetValues(ret_values, 0); } bool OS::compileFile(const String& p_filename, bool required) { String filename = resolvePath(p_filename); String compiled_filename = getCompiledFilename(filename); bool sourcecode_file_exist = isFileExist(filename); bool compiled_file_exist = isFileExist(compiled_filename); if(compiled_file_exist && sourcecode_file_exist){ if(core->settings.primary_compiled_file || checkFileUsage(filename, compiled_filename) == LOAD_COMPILED_FILE){ sourcecode_file_exist = false; }else{ compiled_file_exist = false; } } if(!sourcecode_file_exist && !compiled_file_exist){ if(required){ core->error(OS_E_ERROR, String::format(this, OS_TEXT("required filename %s is not exist"), p_filename.toChar())); return false; } core->error(OS_E_WARNING, String::format(this, OS_TEXT("filename %s is not exist"), p_filename.toChar())); return false; } if(!sourcecode_file_exist){ OS_ASSERT(compiled_file_exist); Core::Program * prog = new (malloc(sizeof(Core::Program) OS_DBG_FILEPOS)) Core::Program(this); prog->filename = compiled_filename; Core::FileStreamReader prog_file_reader(this, compiled_filename); Core::MemStreamWriter prog_file_data(this); prog_file_data.writeFromStream(&prog_file_reader); Core::MemStreamReader prog_reader(NULL, prog_file_data.buffer.buf, prog_file_data.getSize()); String debug_info_filename = getDebugInfoFilename(filename); if(isFileExist(debug_info_filename)){ Core::FileStreamReader debug_info_file_reader(this, debug_info_filename); Core::MemStreamWriter debug_info_file_data(this); debug_info_file_data.writeFromStream(&debug_info_file_reader); Core::MemStreamReader debug_info_reader(NULL, debug_info_file_data.buffer.buf, debug_info_file_data.getSize()); if(!prog->loadFromStream(&prog_reader, &debug_info_reader)){ prog->release(); return false; } }else if(!prog->loadFromStream(&prog_reader, NULL)){ prog->release(); return false; } prog->pushStartFunction(); prog->release(); return true; } Core::FileStreamReader file(this, filename); if(!file.f){ core->error(OS_E_ERROR, String::format(this, OS_TEXT("error open filename %s"), p_filename.toChar())); return false; } Core::MemStreamWriter file_data(this); file_data.writeFromStream(&file); Core::Tokenizer tokenizer(this); tokenizer.parseText((OS_CHAR*)file_data.buffer.buf, file_data.buffer.count, filename); Core::Compiler compiler(&tokenizer); return compiler.compile(); } bool OS::compile(const String& str) { if(str.getDataSize() == 0){ return false; } Core::Tokenizer tokenizer(this); tokenizer.parseText(str.toChar(), str.getLen(), String(this)); Core::Compiler compiler(&tokenizer); return compiler.compile(); } bool OS::compile() { String str = toString(-1); pop(1); return compile(str); } int OS::call(int params, int ret_values) { return core->call(params, ret_values); } int OS::eval(const OS_CHAR * str, int params, int ret_values) { return eval(String(this, str), params, ret_values); } int OS::eval(const String& str, int params, int ret_values) { compile(str); pushNull(); move(-2, 2, -2-params); return core->call(params, ret_values); } int OS::require(const OS_CHAR * filename, bool required, int ret_values) { return require(String(this, filename), required, ret_values); } int OS::require(const String& filename, bool required, int ret_values) { getGlobal(OS_TEXT("require")); pushGlobals(); pushString(filename); pushBool(required); return call(2, ret_values); } int OS::getSetting(OS_ESettings setting) { switch(setting){ case OS_SETTING_CREATE_DEBUG_INFO: return core->settings.create_debug_info; case OS_SETTING_CREATE_DEBUG_OPCODES: return core->settings.create_debug_opcodes; case OS_SETTING_CREATE_COMPILED_FILE: return core->settings.create_compiled_file; case OS_SETTING_PRIMARY_COMPILED_FILE: return core->settings.primary_compiled_file; } return -1; } int OS::setSetting(OS_ESettings setting, int value) { struct Lib { static int ret(bool& cur_value, int new_value) { int old = cur_value; cur_value = new_value ? true : false; return old; } }; switch(setting){ case OS_SETTING_CREATE_DEBUG_INFO: return Lib::ret(core->settings.create_debug_info, value); case OS_SETTING_CREATE_DEBUG_OPCODES: return Lib::ret(core->settings.create_debug_opcodes, value); case OS_SETTING_CREATE_COMPILED_FILE: return Lib::ret(core->settings.create_compiled_file, value); case OS_SETTING_PRIMARY_COMPILED_FILE: return Lib::ret(core->settings.primary_compiled_file, value); } return -1; } int OS::gc() { return core->gcStep(); } void OS::gcFull() { core->gcFull(); } void OS::triggerError(int code, const OS_CHAR * message) { core->error(code, message); } void OS::triggerError(int code, const String& message) { core->error(code, message); } // ===================================================================== // ===================================================================== // ===================================================================== #define OS_QSORT_CUTOFF 8 static void qsortSwap(char *a, char *b, unsigned width) { char tmp; if(a != b) { if(width == sizeof(void*)){ void * tmp = *(void**)a; *(void**)a = *(void**)b; *(void**)b = tmp; return; } if(width >= 16 && width <= 256){ void * tmp = alloca(width); OS_MEMCPY(tmp, a, width); OS_MEMCPY(a, b, width); OS_MEMCPY(b, tmp, width); return; } while(width--){ tmp = *a; *a++ = *b; *b++ = tmp; } } } static void qsortShortsort(OS * os, char *lo, char *hi, unsigned width, int (*comp)(OS*, const void *, const void *, void*), void * user_params) { char *p, *max; while (hi > lo) { max = lo; for (p = lo + width; p <= hi; p += width) if (comp(os, p, max, user_params) > 0) max = p; qsortSwap(max, hi, width); hi -= width; } } void OS::qsort(void *base, unsigned num, unsigned width, int (*comp)(OS*, const void *, const void *, void*), void * user_params) { char *lo, *hi; char *mid; char *l, *h; unsigned size; char *lostk[30], *histk[30]; int stkptr; if (num < 2 || width == 0) return; stkptr = 0; lo = (char*)base; hi = (char*)base + width * (num - 1); recurse: size = (hi - lo) / width + 1; if (size <= OS_QSORT_CUTOFF) { qsortShortsort(this, lo, hi, width, comp, user_params); } else { mid = lo + (size / 2) * width; qsortSwap(mid, lo, width); l = lo; h = hi + width; for (;;) { do { l += width; } while (l <= hi && comp(this, l, lo, user_params) <= 0); do { h -= width; } while (h > lo && comp(this, h, lo, user_params) >= 0); if (h < l) break; qsortSwap(l, h, width); } qsortSwap(lo, h, width); if (h - 1 - lo >= hi - l) { if (lo + width < h) { lostk[stkptr] = lo; histk[stkptr] = h - width; ++stkptr; } if (l < hi) { lo = l; goto recurse; } } else { if (l < hi) { lostk[stkptr] = l; histk[stkptr] = hi; ++stkptr; } if (lo + width < h) { hi = h - width; goto recurse; } } } --stkptr; if (stkptr >= 0) { lo = lostk[stkptr]; hi = histk[stkptr]; goto recurse; } }
Python
UTF-8
3,250
2.921875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, mixture, model_selection import sklearn from scipy import stats from mpl_toolkits.mplot3d import Axes3D plt.style.use('classic') def plot_2d_density(estimator, X_sample, orig_dens, model_dens, xmin, xmax): fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) fig.subplots_adjust(left=0.05, right=0.95, hspace=0.05, wspace=0.05) ax = ax.ravel() ax[0].imshow(orig_dens, origin='lower', extent=[xmin, xmax, xmin, xmax], cmap=plt.cm.binary) ax[0].set_title("Source Distribution Model") ax[1].scatter(X_sample[:, 0], X_sample[:, 1], color='b', edgecolor='black', s=20, alpha=0.5) ax[1].set_title("Random sample from Source Distribution") ax[1].set_ylabel('$y$') ax[2].imshow(model_dens, origin='lower', extent=[xmin, xmax, xmin, xmax], cmap=plt.cm.binary) ax[2].set_title("Density Model") if isinstance(estimator, sklearn.mixture.GaussianMixture): X_new = estimator.sample(1000)[0] else: X_new = estimator.sample(1000) ax[3].scatter(X_new[:, 0], X_new[:, 1], color='r', edgecolor='black', alpha=0.5, s=20) ax[3].set_title("Random Generated Data from Density-Model") for ax in fig.axes: ax.set_xlim(xmin, xmax) ax.set_ylim(xmin, xmax) ax.set_xlabel('$x$') fig.suptitle("Understanding Density Estimation Algorithm", size=20) #create input grid of data xmin = -3 xmax = 9 n = 100 xx, yy = np.meshgrid(np.linspace(xmin, xmax, n), np.linspace(xmin, xmax, n)) Xgrid = np.column_stack( (xx.ravel(), yy.ravel()) ) #create a combined multivariate gaussian distribution mu_vec = [ [0,0], [5,3] ] cov_mat = [ [[1,0.5],[0.5,1]], [[1,0.8],[0.8,1]]] f = [0.5, 0.5] orig_dens = sum([f[i] * stats.multivariate_normal(mean=mu_vec[i], cov=cov_mat[i]).pdf(Xgrid) for i in range(len(mu_vec)) ]) orig_dens = orig_dens.reshape(xx.shape) #randomly sample from combined multivariate gaussian distribution N = 300 X_sample = np.concatenate([ stats.multivariate_normal(mean=mu_vec[i], cov=cov_mat[i]).rvs(int(f[i]*N)) for i in range(len(mu_vec)) ]) #using GMM gmm_estimator = mixture.GaussianMixture() gmm_params = {'n_components': np.arange(1, 10, 1) } gmm_grid_estimator = model_selection.GridSearchCV(gmm_estimator, gmm_params) gmm_grid_estimator.fit(X_sample) gmm_best_estimator = gmm_grid_estimator.best_estimator_ model_dens = np.exp(gmm_best_estimator.score_samples(Xgrid)) model_dens = model_dens.reshape(xx.shape) plot_2d_density(gmm_best_estimator, X_sample, orig_dens, model_dens, xmin, xmax) #using KDE kde_estimator = neighbors.KernelDensity(kernel='gaussian') kde_params = {'bandwidth': np.logspace(-1, 1, 20)} kde_grid_estimator = model_selection.GridSearchCV(kde_estimator, kde_params) kde_grid_estimator.fit(X_sample) kde_best_estimator = kde_grid_estimator.best_estimator_ model_dens = np.exp(kde_best_estimator.score_samples(Xgrid)) model_dens = model_dens.reshape(xx.shape) plot_2d_density(kde_best_estimator, X_sample, orig_dens, model_dens, xmin, xmax)
Markdown
UTF-8
2,415
3.078125
3
[]
no_license
# OWDataExtractor Workshop tool for recording tournaments and exporting them as data ## Import code: F4M6WT ------- ### SPECIAL THANKS TO ZEZOMBYE FOR [OVERPY](https://github.com/Zezombye/overpy) I use overpy's decompiler to extract the data. Without it this project would have been a *huge* pain in the ass. ------- # HOW TO USE IT 1. As the round is ending, go into the workshop inspector. ![inspector](docs/images/inspector.png) 2. Wait for this list to fill up with the names of all the players: Bad: ![list_not_full](docs/images/list_not_full.png) Good: ![list_not_full](docs/images/list_full.png) 3. Click on the button labeled `(x)` ![variable_button](docs/images/variable_button.png) 4. Go to [the website](https://protowalker.github.io/OWDataExtractor) and paste into the box labeled "Input data from Overwatch.." The data will be parsed into nice JSON for you to read in the bottom box. ### Hey! Is this data from a tournament or PUG? Consider making a pull request to https://github.com/Protowalker/OWDataExtractor_Dataset with your data. We're trying to compile a dataset for use in statistics and the creation of training modes -- maybe even, with enough data, an AI! ------------- # HOW IT WORKS EVENTS: One array deep is the round. The next array deep is chunks of 50 events There are 5 arrays inside of each chunk; each array is 50 long The first array is timestamps; second is type (an enum, next post will have that), 3rd is the name of the attacker/healer, 4th is the name of the victim/healee, 5th is the associated value (the damage amount, the healing amount, or the direction of knockback) For the type, 0 = Damage, 1 = Healing, 2 = Final Blow, 3 = Knockback -------- DATA: One array deep is the round. Two arrays is the player. Next is chunks of 50 pieces of data Each chunk is made up of 50 elements, each one representing a single timestamp 0: MatchTime() + Millis, 1: EP_Alive, 2: EP_Position, 3: EP_Direction, 4: EP_Health, 5: EP_Velocity, 6: abilityFlags EP = Event Player. Pretty self-explanatory. Ability Flags is special ```cs enum Ability { Ability1 = 1, Ability2 = 2, PrimaryFire = 4, SecondaryFire = 8, Melee = 16, Ultimate = 32 } ``` It's equal to what abilities are active during that tick. Data is taken for all players at a 5 second interval but if I can I'm going to up it to 1 second.
C
UTF-8
2,357
2.578125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 1999-2016 University of Chicago * * 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 "globus_i_dsi_rest.h" /** * @file error_is_retryable.c Check if error is transient error */ /** * @brief Check if an error is transient * @ingroup globus_dsi_rest * @details * This function checks whether the error object referenced by result * is a potentially transient network error. It returns true if the * result does not seem to indicate a non-recoverable error. * * @param[in] result * The result to check to see if the error might be handled by retrying * the operation. */ bool globus_dsi_rest_error_is_retryable( globus_result_t result) { bool retryable = false; int rc; GlobusDsiRestEnter(); if (result == GLOBUS_SUCCESS) { retryable = true; } else { globus_object_t *err = globus_error_peek(result); if (globus_error_match(err, GLOBUS_DSI_REST_MODULE, GLOBUS_DSI_REST_ERROR_CURL)) { char *msg = globus_error_print_friendly(err); char *p = strstr(msg, "libcurl error "); if (p) { if (sscanf(p, "libcurl error %d", &rc) == 1) { switch (rc) { case CURLE_COULDNT_RESOLVE_PROXY: case CURLE_COULDNT_RESOLVE_HOST: case CURLE_COULDNT_CONNECT: retryable = true; break; } } } } } GlobusDsiRestExitBool(retryable); return retryable; } /* globus_dsi_rest_error_is_retryable() */
Java
UTF-8
692
2.515625
3
[]
no_license
/* * (c) 2016 tylerhyperHD */ package com.tylerhyperhd.profreedommod; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; public class ConfigGrabber { private static ProFreedomMod plugin; public ConfigGrabber(ProFreedomMod plugin) { ConfigGrabber.plugin = plugin; } public String getOwner() { FileConfiguration config = plugin.getDefaultConfig(); return config.getString("server_owner"); } public boolean isOwner(Player player) { if (player.getName().equals(getOwner())) { return true; } else { return false; } } }
Java
UTF-8
7,627
2.5625
3
[]
no_license
/** * */ package twt.controller.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Query; import twt.controller.MyGlobal; import twt.controller.dao.imp.IExpress; import twt.model.Express; import twt.model.Household; /** * @author 我啊 * */ public class ExpressDao implements IExpress { public ExpressDao() { //MyGlobal.init(); } @Override public List<Express> QueryExpressByPhone(String phone) { List<Express> res = new ArrayList<Express>(); SQLDao.init(); String sql="select * from Express where phone ="+phone; try { ResultSet rs = SQLDao.stmt.executeQuery(sql); while(rs.next()){ // 通过字段检索 int id = rs.getInt("id"); String number = rs.getString("number"); Date time =rs.getDate("time"); int picked=rs.getInt("picked"); Household h=new Household(); h.setPhone(phone); Express e=new Express(h,number,time,picked); e.setId(id); res.add(e); } // 完成后关闭 rs.close(); } catch (SQLException e) { e.printStackTrace(); } return res; } @Override public List<Express> QueryUnpickedExpressByPhone(String phone) { List<Express> res = new ArrayList<Express>(); SQLDao.init(); String sql="select * from Express where phone = "+phone+" and picked = 0"; try { ResultSet rs = SQLDao.stmt.executeQuery(sql); while(rs.next()){ // 通过字段检索 int id = rs.getInt("id"); String number = rs.getString("number"); Date time =rs.getDate("time"); int picked=rs.getInt("picked"); Household h=new Household(); h.setPhone(phone); Express e=new Express(h,number,time,picked); e.setId(id); res.add(e); } // 完成后关闭 rs.close(); } catch (SQLException e) { e.printStackTrace(); } return res; } @Override public int PickExpress(int id) { int r=0; SQLDao.init(); String sql="UPDATE `Express` SET `picked`='"+1+"' WHERE (`id`='"+id+"') LIMIT 1"; try { SQLDao.stmt.execute(sql); r=1; } catch (SQLException e) { e.printStackTrace(); } // MyGlobal.begintrans(); // try { // Express old=(Express) MyGlobal.session.get(Express.class, id); // old.setPicked(1); // MyGlobal.session.update(old); // MyGlobal.commit(); // r=1; // }catch (Exception e) { // MyGlobal.rollback(); // } return r; } public static String fmttime(Date d) { String t=d.getYear()+"-"+d.getMonth()+"-"+d.getDate() +" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds(); return t; } @Override public int AddExpress(Express exp) { int r=0; SQLDao.init(); String sql="INSERT INTO `Express` (`number`, `time`, `phone`, `picked`) VALUES (" + "'"+exp.getNumber()+"', '"+fmttime(exp.getTime())+"', '" +exp.getHousehold().getPhone()+"', '"+exp.getPicked()+"')"; try { SQLDao.stmt.execute(sql); r=1; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //SQLDao.close(); // MyGlobal.begintrans(); // try { // // // Query query = MyGlobal.session.createQuery("from Household where phone=?"); // query.setParameter(0, exp.getHousehold().getPhone()); // List<Household> res; // res=query.list(); // Household h=res.get(0); // //System.out.println(h.getName()); // Household hh=(Household) MyGlobal.session.load(Household.class, h.getId()); // System.out.println(hh.getName()); // System.out.println(exp.getTime()); // exp.setHousehold(hh); // // // MyGlobal.session.save(exp); // MyGlobal.commit(); // r=exp.getId(); // }catch (Exception e) { // System.out.println("失败"+e.toString()); // MyGlobal.rollback(); // } return r; } @Override public int DeleteExpress(int id) { int r=0; String sql="DELETE FROM `Express` WHERE (`id`='"+id+"')"; SQLDao.init(); try { SQLDao.stmt.execute(sql); r=1; } catch (SQLException e) { e.printStackTrace(); } // MyGlobal.begintrans(); // try { // MyGlobal.session.delete(MyGlobal.session.get(Express.class, id)); // MyGlobal.commit(); // r=1; // }catch (Exception e) { // System.out.println("失败"+e.toString()); // MyGlobal.rollback(); // } return r; } @Override public int UpdateExpress(int id, Express exp) { int r=0; SQLDao.init(); String sql="UPDATE `Express` SET `number`='"+exp.getNumber()+"', " + "`time`='"+fmttime(exp.getTime())+"', `phone`='"+exp.getHousehold().getPhone()+"'," + " `picked`='"+exp.getPicked()+"' WHERE (`id`='"+id+"') LIMIT 1"; try { SQLDao.stmt.execute(sql); r=1; } catch (SQLException e) { e.printStackTrace(); } // MyGlobal.begintrans(); // try { // Express old=(Express) MyGlobal.session.get(Express.class, id); // old.setHousehold(exp.getHousehold()); // old.setNumber(exp.getNumber()); // old.setPicked(exp.getPicked()); // old.setTime(exp.getTime()); // MyGlobal.session.update(old); // MyGlobal.commit(); // r=1; // }catch (Exception e) { // MyGlobal.rollback(); // } return r; } @Override public List<Express> QueryExpress(int num) { List<Express> res = new ArrayList<Express>(); SQLDao.init(); String sql="select * from Express"+(num>0?" limit "+num:" "); try { ResultSet rs = SQLDao.stmt.executeQuery(sql); while(rs.next()){ // 通过字段检索 int id = rs.getInt("id"); String number = rs.getString("number"); String phone = rs.getString("phone"); Date time =rs.getDate("time"); int picked=rs.getInt("picked"); Household h=new Household(); h.setPhone(phone); Express e=new Express(h,number,time,picked); e.setId(id); res.add(e); } // 完成后关闭 rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Query query = MyGlobal.session.createQuery("from Express"); // if(num>0) { // res =query.setMaxResults(num).list(); // }else { // res =query.list(); // } return res; } @Override public List<Express> QueryUnpickedExpress(int num) { List<Express> res = new ArrayList<Express>(); SQLDao.init(); String sql="select * from Express where picked = 0"+(num>0?" limit "+num:" "); try { ResultSet rs = SQLDao.stmt.executeQuery(sql); while(rs.next()){ // 通过字段检索 int id = rs.getInt("id"); String number = rs.getString("number"); Date time =rs.getDate("time"); int picked=rs.getInt("picked"); String phone = rs.getString("phone"); Household h=new Household(); h.setPhone(phone); Express e=new Express(h,number,time,picked); e.setId(id); res.add(e); } // 完成后关闭 rs.close(); } catch (SQLException e) { e.printStackTrace(); } return res; } }
C#
UTF-8
275
2.734375
3
[]
no_license
private delegate void YourDelegate(obj param1,obj param2); private void YourFunction(obj param1,obj param2) { //Write Code Here } //Call this from your Thread this.Invoke(new YourDelegate(YourFunction), new object[] { param1,param2});
Shell
UTF-8
402
2.59375
3
[]
no_license
#!/bin/sh VERSION=0.2.7 tar --files-from=file.list -xzvf ../libspectre-$VERSION.tar.gz mv libspectre-$VERSION libspectre-$VERSION-orig cp -rf ./libspectre-$VERSION-new ./libspectre-$VERSION diff -b --unified -Nr libspectre-$VERSION-orig libspectre-$VERSION > libspectre-$VERSION-gs.patch mv libspectre-$VERSION-gs.patch ../patches rm -rf ./libspectre-$VERSION rm -rf ./libspectre-$VERSION-orig
Swift
UTF-8
2,066
2.859375
3
[ "MIT" ]
permissive
import Foundation public struct TypeParser { public static let `default` = TypeParser() /// The types that will be used to parse data. /// /// Types are used in order. The first one in this array that matches the field mode (binary or text) and type id will be used to parse the data. You can change how data will be parsed by adding to or rearanging the types. For instance, to always return Int instead of specific int sizes like Int16, you can do `types.insert(Int.self, at: 0)`, which will force Int to be used before the other types. var types: [PostgresCodable.Type] = [ Int16.self, UInt16.self, Int32.self, UInt32.self, Int64.self, UInt64.self, Int.self, UInt.self, Bool.self, OID.self, Date.self, UUID.self, String.self, ] public init() { } public func parse(_ data: Slice<Data>, for field: Field) -> Any? { for type in types { guard type.pgTypes.contains(field.dataTypeID) else { continue } switch field.mode { case .text: guard let type = type as? PostgresTextDecodable.Type else { continue } guard let text = String(data) else { return nil } return type.init(pgText: text, type: field.dataTypeID) case .binary: guard let type = type as? PostgresBinaryDecodable.Type else { continue } return type.init(pgBinary: data, type: field.dataTypeID) } } switch field.mode { case .text: guard let text = String(data) else { return nil } return text case .binary: return data } } public func parse<T: PostgresCodable>(_ data: Slice<Data>, for field: Field) -> T? { guard T.pgTypes.contains(field.dataTypeID) else { return nil } switch field.mode { case .text: guard let type = T.self as? PostgresTextDecodable.Type else { return nil } guard let text = String(data) else { return nil } return type.init(pgText: text, type: field.dataTypeID) as? T case .binary: guard let type = T.self as? PostgresBinaryDecodable.Type else { return nil } return type.init(pgBinary: data, type: field.dataTypeID) as? T } } }
Go
UTF-8
1,927
2.84375
3
[ "Apache-2.0" ]
permissive
package core import ( "io" "net" log "github.com/kermitbu/grapes/log" ) // InitConnectAsServer a func (c *CoreServer) InitConnectAsServer() { addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:"+*port) if err != nil { log.Fatal(err.Error()) } listen, err := net.ListenTCP("tcp", addr) defer listen.Close() if err != nil { log.Fatal(err.Error()) } log.Info("服务器正常启动,开始监听%v端口", *port) // 监听 go func(listen *net.TCPListener) { for { conn, err := listen.Accept() if err != nil { log.Fatal(err.Error()) } go c.handleServerConn(conn) } }(listen) // 处理 go func() { log.Debug("Channel开始等待数据") buffer := <-BufferChan log.Debug("从Channel中读取出数据:%v", buffer) }() complete := make(chan int, 1) <-complete } func (c *CoreServer) handleServerConn(conn net.Conn) { log.Info("===>>> New Connection ===>>>") head := new(MessageHead) unhandledData := make([]byte, 0) DISCONNECT: for { buf := make([]byte, BufLength) for { n, err := conn.Read(buf) if err != nil && err != io.EOF { log.Error("读取缓冲区出错,有可能是连接断开了: %v", err.Error()) break DISCONNECT } unhandledData = append(unhandledData, buf[:n]...) if n != BufLength { break } } if len(unhandledData) == 0 { log.Error("读取到的数据长度为0,有可能是连接断开了") break } log.Debug("接收到数据:%v", unhandledData) for nil == head.Unpack(unhandledData) { log.Debug("解析出消息:%v", unhandledData) msgLen := head.BodyLen + uint16(head.HeadLen) msgData := unhandledData[:msgLen] unhandledData = unhandledData[msgLen:] BufferChan <- msgData c.deliverMessage(conn, head, msgData[head.HeadLen:]) } } log.Info("===>>> Connection closed ===>>>") }
Java
UTF-8
1,082
2.40625
2
[]
no_license
package support.user.controler; import java.util.HashMap; import java.util.Map; /** * * @author marciano */ public class NodoClient { private String user; private String addressIp; private long time; private Map<String, Boolean> mapListaUrl = new HashMap<String, Boolean>(); public void addUrl(String url, boolean sw) { mapListaUrl.put(url, sw); } public boolean existeUrl(String url) { // return mapListaUrl.get(url); return true; } /** * @return the user */ public String getUser() { return user; } /** * @param user * the user to set */ public void setUser(String user) { this.user = user; } /** * @return the addressIp */ public String getAddressIp() { return addressIp; } /** * @param addressIp * the addressIp to set */ public void setAddressIp(String addressIp) { this.addressIp = addressIp; } /** * @return the time */ public long getTime() { return time; } /** * @param time * the time to set */ public void setTime(long time) { this.time = time; } }
Markdown
UTF-8
3,699
3.03125
3
[]
no_license
## 操作场景 云数据库 SQL Server 支持通过控制台的**数据库管理**页创建数据库,并支持对数据库授权帐号访问。 ## 单实例可创建数据库数量 >! >- 当双节点(原高可用版/集群版)实例的数据库数量大于100时,必须要设置参数 max worker threads 的值为20000。如果使用默认值0,则无法创建数量100以上的数据库。设置方法请参见 [设置实例参数](https://cloud.tencent.com/document/product/238/59255)。 >- 为保证实例的稳定性,当实例 CPU 核数等于1时,不建议放开数据库数量限制,保持为70个。 > SQL Server 2008 R2 Enterprise 版本不支持放开数量限制,其数据库最大数量为70,其他 SQL Server 实例的数据库数量受实例 CPU 核数限制,详细计算公式如下: - **双节点(原高可用版)** 2012 Standard/Enterprise 2014 Standard/Enterprise 2016 Standard/Enterprise 最大数据库数量为: ![](https://qcloudimg.tencent-cloud.cn/raw/bc575b0f70313e573d6c13a4f745743e.png) 即 CPU 核数开二次方后保留一位小数,再乘以40,然后加上80,假设获得值为 X,最大数据库数量取 X 或300间的最小值。例如:SQL Server 2014 Enterprise(4核16GB)实例,最大支持160个数据库。 - **双节点(原集群版)** 2017 Enterprise 2019 Enterprise 最大数据库数量为: ![](https://qcloudimg.tencent-cloud.cn/raw/b9290b5f533385274696f5aabca43134.png) 即 CPU 核数开二次方后保留一位小数,再乘以40,然后加上120,假设获得值为 Y,最大数据库数量取 Y 或340间的最小值。例如:SQL Server 2017 Enterprise(4核16GB)实例,最大支持200个数据库。 - **单节点(原基础版)** 2008 R2 Enterprise 2012 Enterprise 2014 Enterprise 2016 Enterprise 2017 Enterprise 2019 Enterprise 最大数据库数量为: ![](https://qcloudimg.tencent-cloud.cn/raw/845a879366d20635ed401d042a7229ff.png) 即 CPU 核数开二次方后向下取整,再乘以100,假设获得值为 N,最大数据库数量取 N 或400间的最小值。例如:SQL Server 2017 Enterprise(4核16GB)实例,最大支持200个数据库。 **实例 CPU 核数与各版本最大数据库量对照表** <dx-tabs> ::: 双节点(原高可用版/集群版)最大数据库数量 | CPU 核数 | 双节点2008 R2/2012/2014/2016 Enterprise 版 | 双节点2017/2019 Enterprise 版| |---------|---------|---------| | 1 | 70 | 70 | | 2 | 136 | 176 | | 4 | 160 | 200 | | 8 | 193 | 233 | | 12 | 218 | 258 | | 16 | 240 | 280 | | 24 | 275 | 315 | | 32 | 300 | 340 | | 48 | 300 | 340 | | 64 | 300 | 340 | | 96 | 300 | 340 | ::: ::: 单节点(原基础版)最大数据库数量 | CPU 核数 | 单节点(原基础版) | |---------|---------| | 2 | 100 | | 4 | 200 | | 8 | 200 | | 16 | 400 | | 24 | 400 | ::: </dx-tabs> ## 操作步骤 1. 登录 [SQL Server 控制台](https://console.cloud.tencent.com/sqlserver),在实例列表,单击实例 ID 或**操作**列的**管理**,进入实例管理页面。 2. 在实例管理页面,选择**数据库管理**页,单击**创建数据库**,在弹出的对话框填写相关信息,确认无误后,单击**确定**。 ![](https://main.qcloudimg.com/raw/496bb77b68421cfb5514a753b997faca.png) - 数据库名称:由字母、数字、下划线组成,字母开头,最长32个字符。 - 支持字符集:选择该库采用的字符集,目前已支持大多数原生字符集。 - 授权帐号:可以针对已有帐号对该库进行授权,如未创建帐号,可参见 [创建帐号](https://cloud.tencent.com/document/product/238/7521)。 - 备注说明:输入备注说明,最多256个字符。
C#
UTF-8
1,630
2.546875
3
[]
no_license
using UnityEngine; namespace LastStand { public class SurvivorGenerator { private const int INITIAL_SURVIVORS = 3; private const int GENERIC_SURVIVOR_STAT_VARIANCE = 6; public static void GenerateInitialSurvivors() { GenerateHeroicSurvivorModel(); for (int i = 0; i < INITIAL_SURVIVORS - 1; i++) { GenerateSurvivorModel(); } } public static void GenerateSurvivorModel() { SurvivorModel model = new SurvivorModel(); model.RandomiseValues(); model.FitnessSkill = Random.Range(0, GENERIC_SURVIVOR_STAT_VARIANCE + 1); model.StrengthSkill = Random.Range(0, GENERIC_SURVIVOR_STAT_VARIANCE + 1); model.ShootingSkill = Random.Range(0, GENERIC_SURVIVOR_STAT_VARIANCE + 1); model.Name = SurvivorNameGenerator.GenerateName(model.IsMale); } private const int HEROIC_SURVIVOR_STAT_MIN = 13; private const int HEROIC_SURVIVOR_STAT_MAX = 22; public static void GenerateHeroicSurvivorModel() { SurvivorModel model = new SurvivorModel(); model.RandomiseValues(); model.FitnessSkill = Random.Range(HEROIC_SURVIVOR_STAT_MIN, GENERIC_SURVIVOR_STAT_VARIANCE + 1); model.StrengthSkill = Random.Range(HEROIC_SURVIVOR_STAT_MIN, HEROIC_SURVIVOR_STAT_MAX + 1); model.ShootingSkill = Random.Range(HEROIC_SURVIVOR_STAT_MIN, HEROIC_SURVIVOR_STAT_MAX + 1); model.Name = SurvivorNameGenerator.GenerateName(model.IsMale); } } }
Python
UTF-8
900
2.578125
3
[ "BSD-3-Clause" ]
permissive
import numpy as np import pytest from kiez.neighbors import HNSW, NNG, Annoy, SklearnNN rng = np.random.RandomState(2) @pytest.mark.parametrize("algo_cls", [HNSW, SklearnNN, NNG, Annoy]) def test_str_rep(algo_cls, n_samples=20, n_features=5): source = rng.rand(n_samples, n_features) algo = algo_cls() assert "is unfitted" in str(algo._describe_source_target_fitted()) algo.fit(source, source) assert "is fitted" in str(algo._describe_source_target_fitted()) def test_check_k_value(): with pytest.raises(ValueError) as exc_info: SklearnNN()._check_k_value(k=-1, needed_space=2) assert "Expected" in str(exc_info.value) with pytest.raises(TypeError) as exc_info: SklearnNN()._check_k_value(k="test", needed_space=2) assert "integer" in str(exc_info.value) checked = SklearnNN()._check_k_value(k=3, needed_space=2) assert checked == 2
JavaScript
UTF-8
3,668
2.53125
3
[]
no_license
var express = require('express'); var router = express.Router(); var User = require('./schema'); const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens const config = require('../../config'); // get our config file /** * Register a new User */ router.post('/register', (req, res) => { const newUser = new User({ username: req.body.username, firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, userType: req.body.userType, password: req.body.password }); newUser.save((err, user) => { if (err) { var errors = []; if (err.name == 'ValidationError') { for (field in err.errors) { errors.push(err.errors[field].message); } } return res.status(422).json({ success: false, error: err.name, message: err.message, details: errors }); } else { res.status(201).json({ success: true, message: 'New User Added.', user }); } }); }); router.get('/initialize', (req, res) => { const newUser = new User({ username: 'admin', firstName: 'Administrator', lastName: '', userType: 'ADMIN', password: 'admin' }); newUser.save((err, user) => { if (err) { return res.status(422).json({ success: false, error: err.name, message: err.message }); } else { res.status(201).json({ success: true, message: 'Default Admin Added!', user }); } }); }); router.get('/', (req, res) => { const users = User.find().exec((err, users) => { res.send({ success: true, users }); }); }); router.post('/authenticate', function(req, res) { // find the user User.findOne({ username: req.body.username }, function(err, user) { if (err) throw err; if (!user) { res.status(401).json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { // check if password matches if (user.password != req.body.password) { res.status(401).json({ success: false, message: 'Authentication failed. Wrong password.' }); } else { // if user is found and password is right // create a token var userToken = { username: user.username, userType: user.userType }; var token = jwt.sign(userToken, config.secret, { expiresIn: 1 * 60 * 60 // expires in 1 hours }); // return the information including token as JSON res.json({ success: true, token: token, username: user.username, name: user.firstName, userType: user.userType }); } } }); }); /** * Log out the current user */ router.get('/logout', function(req, res) { const user = req.user; req.logout(); res.status(200).json({ sucess: true, message: "Logged out!", user }); }); module.exports = router;
Python
UTF-8
453
2.953125
3
[]
no_license
class OnMemoryRepository(dict): def __init__(self, factory, keyfunc, dct={}): super(OnMemoryRepository, self).__init__() self.update(dct) self.factory = factory self.keyfunc = keyfunc def get_many(self, keys): return (value for key, value in self.items() if key in keys) def new_item(self): item = self.factory() key = self.keyfunc(item) self[key] = item return item
C++
UTF-8
6,751
2.625
3
[]
no_license
#pragma once #include "allscale/api/user/data/grid.h" #include "ipic3d/app/vector.h" #include "ipic3d/app/parameters.h" #include <map> namespace ipic3d { using coordinate_type = allscale::api::user::data::GridPoint<3>; namespace { std::string getUseCaseName(const UseCase& useCase) { switch(useCase) { case UseCase::Dipole: return "Dipole"; case UseCase::Test: return "Test"; } // adhere to fallback policy in parameter parsing return "Test"; } } /** * Printing support for the use case enum. */ std::ostream& operator<<(std::ostream& out, const UseCase& useCase) { return out << getUseCaseName(useCase); } // TODO: these defaults should not be externally visible namespace { // TODO: check and rename all these fields // Earth parameters static const double Re = 6378137.0; // Earth radius in meters static const double B1 = 3.07e-5; // External magnetic field in Tesla // Other parameters static const double e = 1.602176565e-19; // Elementary charge (Coulomb) static const double m = 1.672621777e-27; // Proton mass (kg) static const double c = 299792458.0; // speed of light (m/s) static const double K = 1e7 * e; // kinetic energy in eV converted to Joules } /** * Holds all properties common to/uniform in a universe that are needed throughout the simulation * */ struct UniverseProperties { // the use case UseCase useCase; // The size of this universe coordinate_type size; // The width of cells Vector3<double> cellWidth; // The timestep double dt; // Speed of light double speedOfLight; // planet radius double planetRadius; // object center Vector3<double> objectCenter; // physical point of origin corresponds to the front lower left corner // by defaul it is {0, 0, 0} Vector3<double> origin; // initial exteranal magnetic field Vector3<double> externalMagneticField; int FieldOutputCycle; int ParticleOutputCycle; std::string outputFileBaseName; UniverseProperties(const UseCase& useCase = UseCase::Dipole, const coordinate_type& size = {1, 1, 1}, const Vector3<double>& cellWidth = {1.0, 1.0, 1.0}, const double dt = 1.0, const double speedOfLight = 1.0, const double planetRadius = 0.0, const Vector3<double>& objectCenter = { 0.0, 0.0, 0.0 }, const Vector3<double>& origin = { 0.0, 0.0, 0.0 }, const Vector3<double>& externalMagneticField = { 0,0,0 }, const int FieldOutputCycle = 100, const int ParticleOutputCycle = 100) : useCase(useCase), size(size), cellWidth(cellWidth), dt(dt), speedOfLight(speedOfLight), planetRadius(planetRadius), objectCenter(objectCenter), origin(origin), externalMagneticField(externalMagneticField), FieldOutputCycle(FieldOutputCycle), ParticleOutputCycle(ParticleOutputCycle) { assert_true(size.x > 0 && size.y > 0 && size.z > 0) << "Expected positive non-zero universe size, but got " << size; assert_true(size.x == size.y && size.y == size.z) << "Expected sizes of universe to be equal (=cubic universe), but got " << size.x << ", " << size.y << ", " << size.z; assert_true(cellWidth.x > 0 && cellWidth.y > 0 && cellWidth.z > 0) << "Expected positive non-zero cell widths, but got " << cellWidth; assert_lt(0, dt) << "Expected positive non-zero time step, but got " << dt; assert_lt(0, speedOfLight) << "Expected positive non-zero speed of light, but got " << speedOfLight; assert_le(0, planetRadius) << "Expected positive or zero object radius, but got " << planetRadius; assert_le(0, FieldOutputCycle) << "Expected positive or zero object field output cycle, but got " << FieldOutputCycle; assert_le(0, ParticleOutputCycle) << "Expected positive or zero object particle output cycle, but got " << ParticleOutputCycle; } UniverseProperties(const Parameters& params) : useCase(params.useCase), size({ params.ncells.x, params.ncells.y, params.ncells.z }), cellWidth({ params.dspace.x, params.dspace.y, params.dspace.z }), dt(params.dt), speedOfLight( params.c ), planetRadius( params.planetRadius ), objectCenter({ params.objectCenter.x, params.objectCenter.y, params.objectCenter.z }), FieldOutputCycle ( params.FieldOutputCycle ), ParticleOutputCycle ( params.ParticlesOutputCycle ) { origin.x = params.objectCenter.x - params.ncells.x * params.dspace.x / 2.0; origin.y = params.objectCenter.y - params.ncells.y * params.dspace.y / 2.0; origin.z = params.objectCenter.z - params.ncells.z * params.dspace.z / 2.0; externalMagneticField = { params.B1.x, params.B1.y, params.B1.z }; } friend std::ostream& operator<<(std::ostream& out, const UniverseProperties& props) { out << "Universe properties:" << std::endl; out << "\tUse Case: " << props.useCase << std::endl; out << "\tSize: " << props.size << std::endl; out << "\tCell width: " << props.cellWidth << std::endl; out << "\tTimestep: " << props.dt << std::endl; out << "\tSpeed of light: " << props.speedOfLight << std::endl; out << "\tPlanet radius: " << props.planetRadius << std::endl; out << "\tObject center: " << props.objectCenter << std::endl; out << "\tOrigin of the domain: " << props.origin << std::endl; out << "\tExternal magnetic field: " << props.externalMagneticField << std::endl; out << "\tFields output cycle: " << props.FieldOutputCycle<< std::endl; out << "\tParticles output cycle: " << props.ParticleOutputCycle<< std::endl; return out; } }; Vector3<double> getOriginOfCell(const coordinate_type& pos, const UniverseProperties& properties) { // do not check for strict domination, as pos could also refer to a field position assert_true(pos.dominatedBy(properties.size)) << "Position " << pos << " is outside universe of size " << properties.size; Vector3<double> tempPos{ (double)pos.x, (double)pos.y, (double)pos.z }; return properties.origin + elementwiseProduct(tempPos, properties.cellWidth); } Vector3<double> getLocationForFields(const coordinate_type& pos, const UniverseProperties& properties) { // do not check for strict domination, as pos could also refer to a field position assert_true(pos.dominatedBy(properties.size + coordinate_type(1))) << "Position " << pos << " is outside universe of size " << properties.size; Vector3<double> tempPos{ (double)pos.x, (double)pos.y, (double)pos.z }; return properties.origin + elementwiseProduct(tempPos, properties.cellWidth); } Vector3<double> getCenterOfCell(const coordinate_type& pos, const UniverseProperties& properties) { assert_true(pos.strictlyDominatedBy(properties.size)) << "Position " << pos << " is outside universe of size " << properties.size; return getOriginOfCell(pos, properties) + properties.cellWidth / 2.0; } }
Markdown
UTF-8
9,334
3.15625
3
[ "MIT" ]
permissive
--- title: 20200420 알고리즘 date: 2020-04-21 01:04:57 category: algorithm --- ### 1. 실패율 <img src="https://user-images.githubusercontent.com/39187116/79473700-78baed00-8040-11ea-8449-9979047b947b.png" width="500" height="500"/> 슈퍼 게임 개발자 오렐리는 큰 고민에 빠졌다. 그녀가 만든 프랜즈 오천성이 대성공을 거뒀지만, 요즘 신규 사용자의 수가 급감한 것이다. 원인은 신규 사용자와 기존 사용자 사이에 스테이지 차이가 너무 큰 것이 문제였다. 이 문제를 어떻게 할까 고민 한 그녀는 동적으로 게임 시간을 늘려서 난이도를 조절하기로 했다. 역시 슈퍼 개발자라 대부분의 로직은 쉽게 구현했지만, 실패율을 구하는 부분에서 위기에 빠지고 말았다. 오렐리를 위해 실패율을 구하는 코드를 완성하라. - 실패율은 다음과 같이 정의한다. - 스테이지에 도달했으나 아직 클리어하지 못한 플레이어의 수 / 스테이지에 도달한 플레이어 수 전체 스테이지의 개수 N, 게임을 이용하는 사용자가 현재 멈춰있는 스테이지의 번호가 담긴 배열 stages가 매개변수로 주어질 때, 실패율이 높은 스테이지부터 내림차순으로 스테이지의 번호가 담겨있는 배열을 return 하도록 solution 함수를 완성하라. ##### 제한사항 - 스테이지의 개수 N은 `1` 이상 `500` 이하의 자연수이다. - stages의 길이는 `1` 이상 `200,000` 이하이다. - stages에는 1이상 `N+1` 이하의 자연수가 담겨있다. - 각 자연수는 사용자가 현재 도전 중인 스테이지의 번호를 나타낸다. - 단, `N + 1` 은 마지막 스테이지(N 번째 스테이지) 까지 클리어 한 사용자를 나타낸다. - 만약 실패율이 같은 스테이지가 있다면 작은 번호의 스테이지가 먼저 오도록 하면 된다. - 스테이지에 도달한 유저가 없는 경우 해당 스테이지의 실패율은 `0` 으로 정의한다. ##### 입출력 예 | N | stages | result | | ---- | ------------------------ | ----------- | | 5 | [2, 1, 2, 6, 2, 4, 3, 3] | [3,4,2,1,5] | | 4 | [4,4,4,4,4] | [4,1,2,3] | #### Solution ```javascript function solution(N, stages) { let tot = stages.length const answer = [] const arr = new Array(N) arr.fill(0) for (const v of stages) { if ( v <= N ) arr[v-1]++ } for (let i=0; i<arr.length; i++){ let fail_rate = 0 if (tot !== 0 && arr[i] !== 0) { fail_rate = arr[i] / tot tot -= arr[i] } answer.push({stage: i+1, fail: fail_rate}) } return answer.sort((a,b) => { if (a.fail === b.fail ) return a.stage - b.stage return b.fail - a.fail }).map(v => v.stage) } ``` - 배열 순회하며 원소 개수 체크 할 때 로직 복습! ### 2. 정수 제곱근 판별 ###### 문제 설명 임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다. n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요. ##### 제한 사항 - n은 1이상, 50000000000000 이하인 양의 정수입니다. ##### 입출력 예 | n | return | | ---- | :----: | | 121 | 144 | | 3 | -1 | ```javascript function solution(n) { const v = n ** (1/2) if (v > 0 && v % 1 === 0) return (v+1) ** 2 else return -1 } ``` - 문제 관련 내장함수 `Math.sqrt(number)` : number의 제곱근을 반환한다. `Math.pow(number, count)` : number의 count 제곱을 반환한다. `Number.isInteger(number)` : number가 **정수** 인지 체크한다. ### 3. 압축 신입사원 어피치는 카카오톡으로 전송되는 메시지를 압축하여 전송 효율을 높이는 업무를 맡게 되었다. 메시지를 압축하더라도 전달되는 정보가 바뀌어서는 안 되므로, 압축 전의 정보를 완벽하게 복원 가능한 무손실 압축 알고리즘을 구현하기로 했다. 어피치는 여러 압축 알고리즘 중에서 성능이 좋고 구현이 간단한 **LZW**(Lempel–Ziv–Welch) 압축을 구현하기로 했다. LZW 압축은 1983년 발표된 알고리즘으로, 이미지 파일 포맷인 GIF 등 다양한 응용에서 사용되었다. LZW 압축은 다음 과정을 거친다. 1. 길이가 1인 모든 단어를 포함하도록 사전을 초기화한다. 2. 사전에서 현재 입력과 일치하는 가장 긴 문자열 `w`를 찾는다. 3. `w`에 해당하는 사전의 색인 번호를 출력하고, 입력에서 `w`를 제거한다. 4. 입력에서 처리되지 않은 다음 글자가 남아있다면(`c`), `w+c`에 해당하는 단어를 사전에 등록한다. 5. 단계 2로 돌아간다. 압축 알고리즘이 영문 대문자만 처리한다고 할 때, 사전은 다음과 같이 초기화된다. 사전의 색인 번호는 정수값으로 주어지며, 1부터 시작한다고 하자. | 색인 번호 | 1 | 2 | 3 | ... | 24 | 25 | 26 | | --------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | | 단어 | A | B | C | ... | X | Y | Z | 예를 들어 입력으로 `KAKAO`가 들어온다고 하자. 1. 현재 사전에는 `KAKAO`의 첫 글자 `K`는 등록되어 있으나, 두 번째 글자까지인 `KA`는 없으므로, 첫 글자 `K`에 해당하는 색인 번호 11을 출력하고, 다음 글자인 `A`를 포함한 `KA`를 사전에 27 번째로 등록한다. 2. 두 번째 글자 `A`는 사전에 있으나, 세 번째 글자까지인 `AK`는 사전에 없으므로, `A`의 색인 번호 1을 출력하고, `AK`를 사전에 28 번째로 등록한다. 3. 세 번째 글자에서 시작하는 `KA`가 사전에 있으므로, `KA`에 해당하는 색인 번호 27을 출력하고, 다음 글자 `O`를 포함한 `KAO`를 29 번째로 등록한다. 4. 마지막으로 처리되지 않은 글자 `O`에 해당하는 색인 번호 15를 출력한다. | 현재 입력(w) | 다음 글자(c) | 출력 | 사전 추가(w+c) | | ------------ | ------------ | ---- | -------------- | | K | A | 11 | 27: KA | | A | K | 1 | 28: AK | | KA | O | 27 | 29: KAO | | O | | 15 | | 이 과정을 거쳐 다섯 글자의 문장 `KAKAO`가 4개의 색인 번호 [11, 1, 27, 15]로 압축된다. 입력으로 `TOBEORNOTTOBEORTOBEORNOT`가 들어오면 다음과 같이 압축이 진행된다. | 현재 입력(w) | 다음 글자(c) | 출력 | 사전 추가(w+c) | | ------------ | ------------ | ---- | -------------- | | T | O | 20 | 27: TO | | O | B | 15 | 28: OB | | B | E | 2 | 29: BE | | E | O | 5 | 30: EO | | O | R | 15 | 31: OR | | R | N | 18 | 32: RN | | N | O | 14 | 33: NO | | O | T | 15 | 34: OT | | T | T | 20 | 35: TT | | TO | B | 27 | 36: TOB | | BE | O | 29 | 37: BEO | | OR | T | 31 | 38: ORT | | TOB | E | 36 | 39: TOBE | | EO | R | 30 | 40: EOR | | RN | O | 32 | 41: RNO | | OT | | 34 | | ### 입력 형식 입력으로 영문 대문자로만 이뤄진 문자열 `msg`가 주어진다. `msg`의 길이는 1 글자 이상, 1000 글자 이하이다. ### 출력 형식 주어진 문자열을 압축한 후의 사전 색인 번호를 배열로 출력하라. ### 입출력 예제 | msg | answer | | -------------------------- | ------------------------------------------------------------ | | `KAKAO` | [11, 1, 27, 15] | | `TOBEORNOTTOBEORTOBEORNOT` | [20, 15, 2, 5, 15, 18, 14, 15, 20, 27, 29, 31, 36, 30, 32, 34] | | `ABABABABABABABAB` | [1, 2, 27, 29, 28, 31, 30] | #### Solution ```javascript function solution(msg) { var answer = []; const alphaMap = new Map() for (let i=65; i<=90; i++) alphaMap.set(String.fromCharCode(i),i-64) let i = 0; let last = 27 while (i<msg.length){ let cnt = 1; while (i+cnt <= msg.length){ const cur = msg.slice(i,i+cnt); if (!alphaMap.has(cur)){ const prev = msg.slice(i, i+cnt-1); answer.push(alphaMap.get(prev)); alphaMap.set(cur, last); last += 1; break; } else if(i+cnt === msg.length){ answer.push(alphaMap.get(cur)) } cnt += 1 } i += cnt - 1 } return answer; } ``` `String.fromCharCode(num)` num에 맞는 아스키코드 문자 return
PHP
UTF-8
360
2.515625
3
[]
no_license
<?php require_once('../db.php'); require_once('../classes/users.classes.php'); /*make sure request is coming from the ID associated with this session (TF)*/ if($_COOKIE['PHPSESSID'] == session_id()){ if ($_POST['get'] == "user" ) { $userObj = new user($DBH); return $userObj->getProfileFromID($_POST['ID']); }else{ echo "Fail"; } } ?>
C++
UTF-8
3,965
3.21875
3
[]
no_license
/* * Name : lab_7.cpp * Author : FILL IN * Description : Working with File I/O */ #include <fstream> #include <iostream> #include <map> #include <string> using std::cout; using std::ifstream; using std::endl; using std::string; using std::map; /* * Open and read the contents of a text file. Each line of the * file will contain a single integer of possible values 10, 20, * 30, 40, or 50. Perform the following operations on the input values: * 10 -- invoke the function OnTen * 20 -- invoke the function OnTwenty * 30 -- invoke the function OnThirty * 40 -- invoke the function OnForty * 50 -- invoke the function OnFifty * any other value -- invoke the function OnError * </ul> * @param string filename - A string containing the name of the file to * be processed * @return bool - True if filename was successfully opened and processed, * else false */ bool ProcessFile(string filename); // For testing (DO NOT ALTER) #include <cctype> #include <vector> map<int, int> counters; void OnTen(); void OnTwenty(); void OnThirty(); void OnForty(); void OnFifty(); void OnError(); void UnitTest(); void Test(bool test, int line_number, string more_info = "", string yours = "!", string actual = "!"); void OutputFailedTests(); unsigned int ut_passed = 0, ut_failed = 0, ut_total = 0, num_of_tests = 7; std::vector<int> failed_tests; // Program Execution Starts Here int main() { // To test your code (DO NOT ALTER) UnitTest(); // This ends program execution return 0; } // CODE HERE -- FUNCTION DEFINITION // For testing (DO NOT ALTER) void UnitTest() { cout << string(40, '-') << endl; cout << "UNIT TEST:\n" << string(40, '-') << endl; if (num_of_tests != 0) cout << "Total Number of Tests: " << num_of_tests << endl; string yours = "", actual = ""; // Tests counters[10] = 0, counters[20] = 0, counters[20] = 0, counters[40] = 0, counters[50] = 0, counters[99] = 0; ProcessFile("lab_7_input.txt"); Test(counters[10] == 15, __LINE__, "Counting 10s"); Test(counters[20] == 14, __LINE__, "Counting 20s"); Test(counters[30] == 13, __LINE__, "Counting 30s"); Test(counters[40] == 12, __LINE__, "Counting 40s"); Test(counters[50] == 11, __LINE__, "Counting 50s"); Test(counters[99] == 35, __LINE__, "Counting Errors"); Test(ProcessFile("non-existent-file.txt") == false, __LINE__, "Processing non-existent file"); cout << string(40, '-') << endl; cout << "Passed: " << ut_passed << " / " << ut_total << endl; OutputFailedTests(); cout << string(40, '-') << endl; cout << "END OF UNIT TEST!\n"; cout << string(40, '-') << endl; cout << "Be sure to run 'make style' to check for any style errors.\n" << "Please note that 'make style' does NOT check variable names or" << " indentation" << endl << endl; } // For testing (DO NOT ALTER) void Test(bool test, int line_number, string more_info, string yours, string actual) { ut_total++; if (test) { cout << "PASSED TEST "; ut_passed++; } else { cout << "FAILED TEST "; ut_failed++; failed_tests.push_back(ut_total); } cout << ut_total << " " << more_info << "!" << endl; if (!test) { if (yours != "!") cout << "Yours: \"" << yours << '"' << endl; if (actual != "!") cout << "Actual: \"" << actual << '"' << endl; cout << " Check Line " << line_number << " for more info" << endl; } } void OutputFailedTests() { if (failed_tests.size()) { cout << "Failed test number(s): "; for (unsigned int i = 0; i < failed_tests.size() - 1; i++) cout << failed_tests.at(i) << ", "; cout << failed_tests.at(failed_tests.size() - 1) << endl; } } void OnTen() { counters[10]++; } void OnTwenty() { counters[20]++; } void OnThirty() { counters[30]++; } void OnForty() { counters[40]++; } void OnFifty() { counters[50]++; } void OnError() { counters[99]++; }
JavaScript
UTF-8
589
2.53125
3
[]
no_license
function tabEvt(el, num){ var num = num || 0; var menu = $(el).children(); var con = $(el + 'Con').children(); var selectItem = $(menu).eq(num); var i = num; selectItem.addClass('active'); con.eq(num).addClass('current'); menu.click(function(){ if(selectItem !== null){ selectItem.removeClass('active'); con.eq(i).removeClass('current'); } selectItem = $(this); i = $(this).index(); selectItem.addClass('active'); con.eq(i).addClass('current'); }); } tabEvt('#tab', 0);
Markdown
UTF-8
628
3.4375
3
[]
no_license
![](./problem.png) ```python # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def myguess(self, curr, max): resp = guess(curr) print curr if resp == 0: return curr if resp == 1: return self.myguess((curr+max+1)//2,max) if resp == -1: return self.myguess((curr)//2,curr) def guessNumber(self, n): """ :type n: int :rtype: int """ return self.myguess(n, n) ```
Java
UTF-8
700
2.21875
2
[ "MIT" ]
permissive
package com.xzymon.persest.model; public class Store { private Long id; private String name; private String city; private String street; private String number; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
C++
UTF-8
483
3.875
4
[]
no_license
#include <iostream> using namespace std; int Sum(int z){ for(int i = 1; i <= z; i++) { cout << "Sum of 1 to " << i << " is " << i*(i+1)/2 << endl; } return i; } int Product(int y){ for(int n = 1; n <= y; n++){ cout << "product of 1 to " << n << " is " << n*n << endl; } return n; } int main(){ int x; cout << "Hello World!" << endl; cout << "What number do you want to pick to get the sum?"; cin >> x; sum(x); product(x); return 0; }
Java
UTF-8
2,682
2.640625
3
[]
no_license
package com.example.myssd.note; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.myssd.note.modul.Link; import java.util.ArrayList; //Custom adapter public class LinkAdapter extends ArrayAdapter<Link> { private Context mContext; private int id; private ArrayList<Link> items; Context ctx; LayoutInflater lInflater; public LinkAdapter(@NonNull Context context, int resource, @NonNull ArrayList<Link> ar) { super(context, resource, ar); mContext = context; id = resource; items = ar; lInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return items.size(); } // position of element @Override public Link getItem(int position) { return items.get(position); } // id @Override public long getItemId(int position) { return position; } @NonNull @Override public View getView(int position, View v, @NonNull ViewGroup parent) // методик, который меняет вид нашей вьюшечки { View mView = v ; if (mView == null) { mView = lInflater.inflate(R.layout.item, parent, false); } Link link = getLink(position); TextView textl = ((TextView) mView.findViewById(R.id.tvDescr)); textl.setText(link.getJust_link()); TextView textr = ((TextView) mView.findViewById(R.id.tvPrice)); textr.setText(link.getDate()); Log.d(link.getDate(),link.getDate()); com.example.myssd.note.modul.Link s = getItem(position); textl.setTextColor(Color.BLACK); textr.setTextColor(Color.BLACK); if(s.getStatus()==1){ mView.setBackgroundColor(mContext.getResources().getColor(R.color.LightGreen)); } else if(s.getStatus()==2){ mView.setBackgroundColor(mContext.getResources().getColor(R.color.Crimson)); } else if(s.getStatus()==3){ mView.setBackgroundColor(mContext.getResources().getColor(R.color.LightGrey)); } else if(s.getStatus()==4){ mView.setBackgroundColor(mContext.getResources().getColor(R.color.LightCyan)); } else if(s.getStatus()==5){ mView.setBackgroundColor(mContext.getResources().getColor(R.color.LightYellow)); } return mView; } // link of position Link getLink(int position) { return ((Link) getItem(position)); } }
Markdown
UTF-8
2,052
2.953125
3
[]
no_license
## Movie Feast An app that uses the [Movies.db API](https://www.themoviedb.org/?language=en) to find the popular movies,Top rated,Now playing and Up coming movies in realtime and inflate the activities with the data of those movies accordingly. <br /> **Things I've Learnt:** * Working with [Movies API](https://www.themoviedb.org/?language=en) * [Networking in Android](https://developer.android.com/training/basics/network-ops/connecting.html) * JSON parsing * Scrolling view * Picasso * Bottom Navigation Bar * Grid View * Play videos in YouTube using implicit intents * Favorite movies tracking * Content Providers * SQLite Databases * Working with URIs * Using share Intent * Handle Requests in absence of network * Offline Storage of favorite movies * Bug fix<br /> **Popular movies in the form of JSON:** <br /> <br /> `https://api.themoviedb.org/3/movie/popular?api_key= <<YOUR_API_KEY>> ` <br /> <br /> `https://api.themoviedb.org/3/movie/top_rated?api_key= <<YOUR_API_KEY>> ` <br /> <br /> **Note:**<br /> Get your API key and place it in the strings.xml file in the resource directory.(NOTE: Marked as TODO in strings.xml file)<br /> ``` xml <string name="API_Key">Your API Key</string> ``` **Show case:**<br /> <img src="assert/popular.png" height=480 width =270 /> <img src="assert/top_rated.png" height=480 width =270 /> <img src="assert/now_playing.png" height=480 width =270 /> <img src="assert/up_coming.png" height=480 width =270 /> <img src="assert/overview.png" height=480 width =270 /> <img src="assert/pre_video.png" height=480 width =270 /> <img src="assert/youtube.png" height=480 width =270 /> <img src="assert/share.png" height=480 width =270 /> <img src="assert/empty_fav.png" height=480 width =270 /> <img src="assert/add_fav.png" height=480 width =270 /> <img src="assert/fav.png" height=480 width =270 /> <img src="assert/rem_fav.png" height=480 width =270 /><br /> **In absence of Network:**<br /> <img src="assert/no_network.png" height=480 width =270 /> <img src="assert/fav_full.png" height=480 width =270 />
Python
UTF-8
1,218
2.546875
3
[]
no_license
#!/usr/bin/env python3 # No configuration required in here, unless you use Windows (see line 12) import os os.chdir('grader') import grader.config os.chdir('..') AssignmentNumber = grader.config.ASSIGNMENT_NUMBER import sys, platform, subprocess EDITOR_CMD = os.environ['EDITOR'] if (platform.system() != 'Windows') else 'notepad.exe' # I don't use Window$, on POSIXy systems this uses the user's $EDITOR (e.g. vim) # Runs the command `vim a b c ...` # Where a, b, c, ... are the grading TeX files for the current assignment and # the current students, and 'vim' is actually the current EDITOR # get usernames from smallusernames.txt usernames = [] with open('grader/usernames.txt') as f: for line in f: usernames += [line.strip()] # this is the filepath to the grading report TeX file, plug in assignment number file_template = 'reports/{}/Assignments/Assignment{}.tex'.format('{}', AssignmentNumber) # and make a list of files after plugging in the usernames files = [] for username in usernames: files += [file_template.format(username)] # build up the command string # e.g. cmd = ['vim', 'file1', 'file2', 'file3', ...] cmd = [EDITOR_CMD] for f in files: cmd += [f] # and run it subprocess.run(cmd)
Python
UTF-8
2,452
3.484375
3
[]
no_license
class Board: def __init__(self, input): self.arr = [[x for x in l if x != '\n'] for l in input] def show(self): return '\n'.join(''.join(x) for x in self.arr) def neighbors(self, y, x, radius=1): return [ self.arr[i][j] if 0 <= i < len(self.arr) and 0 <= j < len(self.arr[0]) and not ((i == y) and (j == x)) else None for j in range(x - radius, x + radius + 1) for i in range(y - radius, y + radius + 1) ] def visible_neighbors(self, y, x): def direction(y, x, dy, dx): if 0 <= y + dy < len(self.arr) and 0 <= x + dx < len(self.arr[0]): if self.arr[y + dy][x + dx] == '.': return direction(y + dy, x + dx, dy, dx) else: return self.arr[y + dy][x + dx] return [ direction(y, x, -1, -1), direction(y, x, -1, +0), direction(y, x, -1, +1), direction(y, x, +0, -1), direction(y, x, +0, +1), direction(y, x, +1, -1), direction(y, x, +1, +0), direction(y, x, +1, +1), ] def cycle(self, max_neighbors=4, neighbors_mode=0): new_arr = [row[:] for row in self.arr] neighbor_func = (self.neighbors, self.visible_neighbors)[neighbors_mode] change = False for row in range(len(self.arr)): for col in range(len(self.arr[row])): if self.arr[row][col] == 'L' and neighbor_func(row, col).count('#') == 0: new_arr[row][col] = '#' change = True if self.arr[row][col] == '#' and neighbor_func(row, col).count('#') >= max_neighbors: new_arr[row][col] = 'L' change = True self.arr = new_arr if not change: return self.occupied() else: return self.cycle(max_neighbors=max_neighbors, neighbors_mode=neighbors_mode) def occupied(self): return sum([x.count('#') for x in self.arr]) def part_one(input): b = Board(input) return b.cycle() def part_two(input): b = Board(input) return b.cycle(max_neighbors=5, neighbors_mode=1) if __name__ in '__main__': input = open('input.txt').readlines() # or sometimes # input = open('input.txt').read() print(part_one(input)) print(part_two(input))
C
UTF-8
1,591
3.671875
4
[]
no_license
#include "rational_numbers.h" #include <stdlib.h> #include <math.h> static int get_gcd(int a, int b) { for (int i = abs(a); i >= 1; i--) { if (a % i == 0 && b % i == 0) { return i; } } return 1; } rational_t reduce(rational_t r) { if (r.numerator == 0) { return (rational_t) { 0, 1 }; } if (r.denominator < 0) { r.numerator *= -1; r.denominator *= -1; } int gcd = get_gcd(r.numerator, r.denominator); return (rational_t) { r.numerator / gcd, r.denominator / gcd }; } rational_t add(rational_t r1, rational_t r2) { return reduce((rational_t) { r1.numerator * r2.denominator + r2.numerator * r1.denominator, r1.denominator * r2.denominator }); } rational_t subtract(rational_t r1, rational_t r2) { return reduce((rational_t) { r1.numerator * r2.denominator - r2.numerator * r1.denominator, r1.denominator * r2.denominator }); } rational_t multiply(rational_t r1, rational_t r2) { return reduce((rational_t) { r1.numerator * r2.numerator, r1.denominator * r2.denominator }); } rational_t divide(rational_t r1, rational_t r2) { return reduce((rational_t) { r1.numerator * r2.denominator, r1.denominator * r2.numerator }); } rational_t absolute(rational_t r) { return reduce((rational_t) { abs(r.numerator), abs(r.denominator) }); } rational_t exp_rational(rational_t r, int n) { return reduce((rational_t) { pow(r.numerator, n), pow(r.denominator, n) }); } float exp_real(int x, rational_t r) { return pow(pow(x, r.numerator), (1 / (float)r.denominator)); }
C++
UTF-8
1,020
2.609375
3
[ "MIT" ]
permissive
#include <ArduinoMessenger.h> Messenger messenger(Serial); message m; byte mes[] = "PUT\n{\"resource\":\"2000 2800 500 1500 100 3000 150 350 350 400 850 2500 2350 2550 600 1300 150 2850 1050 350 750 2700 250 400 950 450 100 2700 250 1900 150 3000 700 \",\"value\":\"38\"};"; //byte mes[] = "GET\n{\"request\":\"get_data\"};"; int size = strlen((char*)mes); int i = 0; void serialPrint(const char * msg, char * content){ Serial.print(msg); if(strlen(content) > 0){ Serial.println(content); } else { Serial.println(F("<empty>")); } } void setup(){ Serial.begin(9600); } void loop(){ delay(1000); i++; Serial.print(F("=================\nIteration nr: ")); Serial.println(i,DEC); byte * msg= (byte*)malloc(size * sizeof(byte)); strcpy((char*)msg, (char*)mes); messenger.parseMessage(&m,msg,size); free(msg); serialPrint("Type: ", m.type); serialPrint("Request: ", m.request); serialPrint("Resource: ", m.resource); serialPrint("Value: ", m.value); messenger.reset(&m); }
Java
UTF-8
875
3.015625
3
[]
no_license
package com.ditedo.kagenoshinobi.naruto.collision; import com.ditedo.kagenoshinobi.naruto.Position; public class CollisionPoint implements Collision { //ATTRIBUTES protected Position position; //CONSTRUCTOR /** Create a point to test collision */ public CollisionPoint(Position position) { this.position = position; } /** Create a point to test collision */ public CollisionPoint(int x, int y) { this.position = new Position(x, y); } //METHODS /** @see Collision#isColliding(CollisionPoint) */ public boolean isColliding(CollisionPoint c) { return this.position.equals(c.position); } /** @see Collision#isColliding(CollisionBox) */ public boolean isColliding(CollisionBox c) { return c.isColliding(this); } /** @see Collision#isColliding(CollisionCircle) */ public boolean isColliding(CollisionCircle c) { return c.isColliding(this); } }
Java
UTF-8
2,636
3.03125
3
[]
no_license
package tests; import java.util.List; import java.util.Random; import org.testng.Assert; import org.testng.annotations.Test; import model.Design.*; import model.Helper.MySQLConn; public class AppointmentTest { @Test public void AppointmentTestNew() { //1:make new appointment by using a random id //2:assert it is in DB by checking with the created id //3:remove it from DB Random rand = new Random(); int randomID = rand.nextInt(1000); String id = "TestID" + randomID; Appointment ap = new Appointment(id,"test","test","test","test"); Assert.assertTrue(ap.appointmentIsInDB(id)); ap.removeAppointment(); } @Test public void AppointmentTestUpdate() { //1:retrieve random id //2:make an appointment object from it //3:update branch column in DB //4:assert if it is updated //5:update it again to the original value List<String> li = MySQLConn.Retrieve("select * from appointment", "AppID"); Random rand = new Random(); int randomID = rand.nextInt(li.size()); Appointment ap = new Appointment(li.get(randomID)); String originalBranchName = ap.getBranch(); String newBranchName = "TestBranch1"; ap.updateAppointment("Branch", newBranchName); Assert.assertTrue(ap.appointmentIsUpdatedDB()); ap.updateAppointment("Branch", originalBranchName); } @Test public void AppointmentTestRead() { //1:retrieve random id //2:check if id exists and is not null by creating appointment object List<String> li = MySQLConn.Retrieve("select * from appointment", "AppID"); Random rand = new Random(); int randomID = rand.nextInt(li.size()); Appointment ap = new Appointment(li.get(randomID)); Assert.assertTrue(ap.getAppID() != null); } @Test public void AppointmentTestDelete() { //1:retrieve random id and create appointment object //2:store contents of object temporarily //3:delete row with retrieved id //4:create an object with previous random id, assert it does not exist //5:create row again with stored data List<String> li = MySQLConn.Retrieve("select * from appointment", "AppID"); Random rand = new Random(); int randomID = rand.nextInt(li.size()); Appointment ap = new Appointment(li.get(randomID)); String appID = ap.getAppID(); String appDate = ap.getAppDate(); String appTime = ap.getAppTime(); String patientID = ap.getPatientID(); String branch = ap.getBranch(); ap.removeAppointment(); Appointment ap2 = new Appointment(li.get(randomID)); Assert.assertTrue(ap2.getAppID() == null); Appointment newAp = new Appointment(appID,patientID,appDate,appTime,branch); } }
Ruby
UTF-8
424
3.703125
4
[]
no_license
print("年齢を入力してください\n") age = gets.chomp.to_i if age < 0 then print("0以上の値を入力してください.\n") elsif age >= 0 and age < 20 then print("未成年です。まだ飲酒できません.\n") elsif age >=20 and age < 40 then print("飲酒できますが、飲み過ぎに注意しましょう.\n") else print("もうそろそろ飲酒を控えた方がいいですよ.\n") end
PHP
UTF-8
809
2.6875
3
[ "MIT" ]
permissive
<?php /** * Boardy * * Simple PHP forum app. * * @package boardy * @author Raphael Marco <pinodex@outlook.ph> * @link http://pinodex.io */ namespace Boardy\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class RecordExistenceValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { if ($constraint->exclude && $constraint->exclude == $value) { return true; } $valid = $constraint->model->where($constraint->row, $constraint->comparator, $value)->exists(); if ($constraint->validate == 'exists' && $valid) { $this->context->addViolation($constraint->message); } if ($constraint->validate == 'not_exists' && !$valid) { $this->context->addViolation($constraint->message); } } }
C++
UTF-8
478
2.703125
3
[]
no_license
#include"cajero.h" int main(){ Cajero *b50 = new Billete50(); Cajero *b20 = new Billete20(); Cajero *b10 = new Billete10(); Cajero *b5 = new Billete5(); // Cajero *b5 = NULL; // el ultimo handler b50->setNext(b20); b20->setNext(b10); b10->setNext(b5); try{ b50->devuelveBilletes(23); } catch(const char* msg){ cerr << msg << endl; } delete b50; delete b20; delete b10; delete b5; return 0; }
Java
UTF-8
3,255
2.03125
2
[ "Apache-2.0" ]
permissive
/* * Sibilla: a Java framework designed to support analysis of Collective * Adaptive Systems. * * Copyright (C) 2020. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.unicam.quasylab.sibilla.langs.pm; import it.unicam.quasylab.sibilla.core.models.CachedValues; import it.unicam.quasylab.sibilla.core.util.values.SibillaDouble; import it.unicam.quasylab.sibilla.core.util.values.SibillaValue; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Function; public class EnvironmentGenerator extends PopulationModelBaseVisitor<Boolean> { private final Map<String,SibillaValue> values; private final Map<String, SibillaValue> parameters; public EnvironmentGenerator() { this(new HashMap<>()); } public EnvironmentGenerator(Map<String, SibillaValue> parameters) { this.values = new HashMap<>(); this.parameters = parameters; } @Override public Boolean visitModel(PopulationModelParser.ModelContext ctx) { ctx.element().forEach(e -> e.accept(this)); return true; } @Override public Boolean visitConst_declaration(PopulationModelParser.Const_declarationContext ctx) { Function<Function<String,Optional<SibillaValue>>,SibillaValue> evaluator = resolver-> ctx.expr().accept(new ExpressionEvaluator(resolver)); values.put(ctx.name.getText(), evaluator.apply(this::getValueOf)); return true; } private Optional<SibillaValue> getValueOf(String name) { if (values.containsKey(name)) return Optional.of(values.get(name)); if (parameters.containsKey(name)) return Optional.of(parameters.get(name)); return Optional.empty(); } @Override public Boolean visitParam_declaration(PopulationModelParser.Param_declarationContext ctx) { if (!parameters.containsKey(ctx.name.getText())) { ExpressionEvaluator evaluator = new ExpressionEvaluator(this::getValueOf); parameters.put(ctx.name.getText(), ctx.expr().accept(evaluator)); } this.values.put(ctx.name.getText(), parameters.get(ctx.name.getText())); return true; } @Override protected Boolean defaultResult() { return true; } public Map<String,SibillaValue> getParameters() { return this.parameters; } @Override protected Boolean aggregateResult(Boolean aggregate, Boolean nextResult) { return aggregate & nextResult; } public Map<String, SibillaValue> getValues() { return this.values; } }
Python
UTF-8
2,518
3.0625
3
[]
no_license
import regex as re import markdown_to_text from wiki import Entry import reddit_utils class Link: """Helper class to format links""" def __init__(self, title, url, tooltip): self.title = title self.url = url self.tooltip = tooltip def __repr__(self): n = Link.markdown_escape(self.title) u = Link.markdown_escape(self.url) if self.tooltip is not None: t = Link.markdown_escape(self.tooltip) return f'[{n}]({u} "{t}")' else: return f'[{n}]({u})' @staticmethod def markdown_escape(url): special = ["\\", "(", ")", "[", "]", "\""] for s in special: url = url.replace(s, "\\" + s) return url @staticmethod def simplify_tooltip(content): content = markdown_to_text.markdown_to_text(content) # no formatting content = " ".join(content.splitlines()) # get rid of newlines return content @staticmethod def from_entry(entry: Entry): title = entry.reference_name() url = reddit_utils.get_url(entry) tooltip = Link.simplify_tooltip(entry.content) return Link(title, url, tooltip) class LinkParser: """Detect request for wiki-links and fulfill them""" def __init__(self, wiki: Entry): self.wiki = wiki @staticmethod def extract_and_replace_links(text, wiki): links = [] # ms = re.findall(r"\[(.+?)\]\((.+?)\)", text) # for m in ms: # title = m.group(1) # url = m.group(2) # full = m.group(0) # if url.strip().startswith("#"): # links.append((title, url, full)) ms = re.findall(r"\[\[(.+?)(\|(.+?))?\]\]", text) for m in ms: full = m.group(0) url = m.group(1) title = m.group(3) or url links.append((title, url, full)) output = [] for title, url, full in links: alias = Entry.normalize(url) entry = wiki.find_child(alias) if entry is None: # couldn't resolve continue link = Link.from_entry(entry) output.append(link) text = text.replace(full, repr(link)) return text, output @staticmethod def bot_comment(content_md, wiki): new, links = LinkParser.extract_and_replace_links(text=content_md, wiki=wiki) comment = "References: " + (" ; ".join(map(repr, links))) return comment
JavaScript
UTF-8
4,371
2.703125
3
[]
no_license
/** * NPM imports */ import React, { Component } from 'react' import Grid from '@material-ui/core/Grid'; import TextField from '@material-ui/core/TextField'; /** * */ import Buttom from '../components/button' /** * */ export default class CreateGroup extends Component { constructor(props) { super(props); this.btnAddmore = this.btnAddmore.bind(this) this.btnDelete = this.btnDelete.bind(this) this.renderItemList = this.renderItemList.bind(this) this.getTextval = this.getTextval.bind(this) this.fnsubmit = this.fnsubmit.bind(this) this.getDateVal = this.getDateVal.bind(this) this.state ={ count:[1]} //this.state = {[{'name':}]} } /** * this function addds count */ btnAddmore =() =>{ const newele = this.state.count.length + 1 this.setState({'count':[...this.state.count, newele]}); } /** * */ btnDelete =() =>{ const val = this.state.count.splice(0,this.state.count.length-1) if(val.length>0) this.setState({ 'count':[ ...val]}) } /** * getTextval */ getTextval = ( event ) => { const val = event.target.value this.setState({[event.target.id]: val}) } renderItemList=()=>{ const itemCount = this.state.count return itemCount.map((item)=>{ return (<Grid key={item} xs={12}container spacing={24} direction="row" justify="center" alignment='center' > <Grid xs={3} style={pad}> <TextField fullWidth id={`${item}-name`} label="name" onChange={this.getTextval}/> </Grid> <Grid xs={3} style={pad}> <TextField fullWidth id={`${item}-phone`} label="phone" onChange={this.getTextval}/> </Grid> <Grid xs={3} style={pad}> <TextField fullWidth id={`${item}-email`} label="email" onChange={this.getTextval}/> </Grid> </Grid>) }) } /** * Master Submit form */ fnsubmit = () =>{ let userList = [] for(let i=1;i<=this.state.count.length;i++){ var obj = { 'name':this.state[i+'-name'], 'phone':this.state[i+'-phone'], 'email':this.state[i+'-email'] } userList.push(obj) } const groupObj = { startdate : this.state.startdate, enddate : this.state.enddate, members: userList } this.props.fnsubmit( groupObj ) } /** * */ getDateVal =( event,type ) =>{ console.log(this.state) const val = event.target.value this.setState({[type]:val}) } /** * Render function */ render() { const count = this.state.count.length const dateProp = { shrink: true } return ( <div> {this.renderItemList()} <Grid xs={12}container spacing={24} direction="row" justify="center" alignment='center'> <Grid style={pad}><Buttom name = {`+${count}`} type="primary" fnclick = {this.btnAddmore} /></Grid> <Grid style={pad}><Buttom name = {`-${count}`} type="secondary" fnclick = {this.btnDelete} /></Grid> </Grid> <Grid xs={12}container spacing={24} direction="row" justify="center" alignment='center' > <Grid xs={3} style={pad}> <TextField fullWidth type='date' id='startdate' label="startdate" onChange={(event)=>{this.getDateVal( event,'startdate')}} InputLabelProps={ dateProp }/> </Grid> <Grid xs={3} style={pad}> <TextField fullWidth type='date' id='enddate' label="enddate" onChange={(event)=>{this.getDateVal( event,'enddate')}} InputLabelProps={ dateProp }/> </Grid> </Grid> <Grid style={pad}><Buttom name = 'submit' type="secondary" fnclick = {this.fnsubmit} /></Grid> </div> ) } } const pad={ padding:'2%' }
Java
UTF-8
885
2.390625
2
[]
no_license
package com.example.practice15.controllers; import com.example.practice15.models.Level; import com.example.practice15.services.LevelService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class LevelController { @Autowired private LevelService levelService; @PostMapping("/addLvl") public void addLevel (@RequestBody Level level) { levelService.addLevel(level); } @GetMapping("/lvl/{id}") public Level findLevel (@PathVariable int id) { return levelService.findLevel(id); } @GetMapping("/lvl") public List<Level> findAll () { return levelService.findAllLevels(); } @DeleteMapping("/delLvl/{id}") public void delLevel (@PathVariable int id) { levelService.deleteLevel(id); } }
PHP
UTF-8
385
2.734375
3
[]
no_license
<?php $servername = "localhost:81"; $username = "root"; $password = ""; $myDB="becas"; try { $conn = new PDO("mysql:host:81=$servername;dbname=$myDB", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); #/echo "Conexión exitosa","<br>"; } catch(PDOException $e) { echo "Conexión fallida: " . $e->getMessage(); } ?>
JavaScript
UTF-8
2,923
2.515625
3
[]
no_license
import mocha from 'mocha'; import chai from 'chai'; import request from 'request-promise-native'; import sinon from 'sinon'; import { INVALID_COORDINATES } from '../src/geolib/GeolibError'; import checkLatLngInState from '../src/checkLatLngInState'; import mockNY from './mock/github/unitedstates/states/NY.json'; const { beforeEach, afterEach, describe, it } = mocha; const { expect, config } = chai; config.includeStack = true; describe('#checkLatLngInState', () => { beforeEach((done) => { sinon .stub(request, 'get') .returns(Promise.resolve(mockNY)); done(); }); afterEach((done) => { request.get.restore(); done(); }); context('when checking a lat,lng in a state', () => { const latitude = 40.718031; const longitude = -73.9583047; it('resolves a promise saying it matches', (done) => { checkLatLngInState(latitude, longitude, 'NY') .then(({ isMatched }) => { expect(isMatched).to.eq(true); done(); }) .catch(done); }); }); context('when checking a lat,lng not in a state', () => { const latitude = 40.7357; const longitude = -74.1724; it('resolves a promise saying it doesn\'t match', (done) => { checkLatLngInState(latitude, longitude, 'NY') .then(({ isMatched }) => { expect(isMatched).to.eq(false); done(); }) .catch(done); }); }); context('when checking a lat,lng against an invalid state', () => { const latitude = 42.6526; const longitude = -73.7562; it('rejects a promise with a 404', (done) => { request.get.restore(); sinon .stub(request, 'get') .returns(Promise.reject({ statusCode: 404})); checkLatLngInState(latitude, longitude, 'BC') .then(() => { done(Error('Promise should be rejected.')); }) .catch(({ statusCode }) => { expect(statusCode).to.eq(404); done(); }) .catch(done); }); }); context('when checking an invalid lat,lng against a state', () => { const latitude = 22; const longitude = 'catch'; it('rejects a promise with an invalid coordinates error', (done) => { checkLatLngInState(latitude, longitude, 'NY') .then(() => { done(Error('Promise should be rejected.')); }) .catch(({ message }) => { expect(message).to.eq(INVALID_COORDINATES); done(); }) .catch(done); }); }); });
Markdown
UTF-8
7,482
3.046875
3
[ "MIT" ]
permissive
--- layout: project title: "COCO: The Prototype" author: kelseydesir tags: [projects] img: COCOChapter2WordCloud.png description: > --- ### What is COCO? [COCO (Characters of Color Organized)](https://docs.google.com/document/d/146NAXoe0QifXFBgJC-15JtdFAJKszeI_ZsfRRzONclE/edit?usp=sharing) --- the prototype is a data-set and collection of close readings of characters of color in 18th Century novels. It is currently in its conceptual and prototypical phase. ### Background The novel is a form of narrative fiction that is both a rhetorical reflection and a projection of experiences (Hulme 156). Specifically, the 18th century novel is a work of fiction that aims to communicate perceived truths. That is, it was often produced with the intent to emulate a sense of verisimilitude, influenced by the belief “that truth can be discovered by the individual through his senses” (Watt 12). The novel became a vector that transmitted content interwoven with both fact and fiction to the reader (Hulme 156-157). Unhindered by its fictive nature, it played an important role in the what Europeans believed (about people of color). ### Objectives/Questions + This project aims to investigate the function of depictions of characters of color and discover the patterns present in the ways in which characters of color are described in 18th century novels. + What are the different ways one can combine close reading and distant reading techniques to analyze the different depictions of characters of color? ### How does COCO work? At the moment, COCO lives on a Google spreadsheet with hyperlinked Google docs. On the spreadsheet “racialized moments,” instances in which characters of color are either the main topic of conversations or participants in a scene that demonstrates clear racial dynamics at play. These moments are broken down and are categorized into metadata. For instance, the ethnicity/nationality, power position, status of freedom, and more are recorded in controlled terms with some bibliographic information. Notably, characters and “entities” (a collective group of characters of color that are not discussed in individual terms) are the foundational unit of the metadata. Each of these logged moments have a corresponding close reading that provide a breakdown of the different racial dynamics present in the “moment” or “scene” and its context within the narrative of the text. ### Method The text(s) were parsed and mimed for interactions and moments that involve characters of color. Defoe’s *Robinson Crusoe* was used as the main sample text. ### Keyword Searching Keyword searching was used to assist in the search for important and interesting scenes. Specifically, racialized terms like “savages, negro, Indian,...” were used to pinpoint these scenes. However, simply searching keywords proved to be tedious, especially when working with the entirety of the work via [Project Gutenberg](http://www.gutenberg.org/ebooks/521?msg=welcome_stranger). ## Using Distant Reading Tools ### Voyant As a result, Voyant, [“a web based reading and analysis environment for digital texts,”](http://voyant-tools.org/) was used to refine the search for “racialized moments.” In addition to incorporating the use of this distant reading tool, a change in approach was made as well. Instead of working with the entire text at a time, the work was analyzed chapter by chapter. For instance, individual chapters of Robinson Crusoe were uploaded to Voyant. Voyant has multiple helpful features that help highlight the words with the highest frequencies in a work. For example, Voyant generates a word cloud that indicates which words were most frequently used in the uploaded text with the size of the word in the cloud being indicative of their frequency. If the name of a character of color was present in the word cloud it could be inferred that a significant number of scenes that center them could be found in that section of the text. Additionally, the frequency of the most used words is also communicated through numeric values. Voyant also allows for the user to see how each use of the word appears in the context of the text. Using Voyant and analyzing the novel chapter by chapter proved to be more effective than the simple keyword searching method. ![Word cloud](/public/img/COCOChapter2WordCloud.png) _Robinson Crusoe Chapter 2_ ### AntConc AntConc facilitated the comparison of Robinson Crusoe to other 18th century literature. Therefore, AntConc, [“a freeware corpus analysis toolkit for concordancing and text analysis,”](http://www.laurenceanthony.net/software/antconc/) was employed to refine my search and analysis. Similar to Voyant, AntConc allows one to see the frequency of the words used and the context of their usage. However, AntConc’s display of this information is more concise and condensed. Additionally, it provides concordance plots, visual representations of the frequency of a word within a text. ![Friday concordance plot](/public/img/COCOFridayConcordancePlot.png) _Concordance plot for Robinson Crusoe’s Friday_ ![Savage concordance plot](/public/img/COCOSavageConcordancePlot.png) _Concordance plot for the word savage_ ### Challenges Although, using both Voyant and AntConc assisted in the targeting of moments to analyze, there were still limitations when trying to use them to facilitate close readings. Specifically, using these tools to find “racialized moments” requires relying on the appearances of search terms. However, a word is a limited marker of representation for a character. A word or a term can be used as a quantifiable unit to trace a character or a group of characters’ presences in a work. That is, these tools were created to help with distant reading and as a result one can overlook essential moments in the plot when using them. A character is more than their name or representative term. It is possible that a key moment about a character can go undetected when only using key terms, in combination with specifically targeting sections of the text where their term/name is high in frequency. As a result, the process of finding key moments in the story arcs of characters of color needed to be supplemented with plot summaries. ### Implications and the Future Moving forward the plan is to expand COCO. This expansion would not only include adding more texts into the corpus, but also searching for more features in the text. For example, it is not only important to search for the presence of characters of color but their absence as well. Are there moments in which white adventurers are in “foreign” lands but make no mention of the people who live there? If characters of color are mentioned are they discussed in individual terms or are they lumped in a large group and treated like background scenery? At the core, COCO is a project that aims to recognize how fiction can be used to present perceived truths and communicate the important influence that these depictions can have when claiming to depict under represented people. ### References Froehlich, Heather. “Corpus Analysis with Antconc.” Programming Historian, 19 June 2015, programminghistorian.org/lessons/corpus-analysis-with-antconc. Hulme, Peter, and Tim Youngs. "Africa / The Congo: The Politics of Darkness." The Cambridge Companion to Travel Writing. Cambridge: Cambridge UP, 2013. 156-73. Print. Watt, Ian. The Rise of the Novel: Studies in Defoe, Richardson and Fielding. London: Bodley Head, 2015. Print.
Markdown
UTF-8
531
2.515625
3
[]
no_license
# CINEMAADDICT It's a service for fans of big movies. Detailed information about the latest hot movies, the ability to select and create your own list of films for viewing, discussion of movies and much more. ## Used technologies: * JS (ECMAScript 6) * ESLint * Build process (Create React App) * AJAX (Fetch) * Used libraries: chart.js, moment ## Cross-browser compatibility * Chrome * Firefox * Safari * Edge ### Site navigation * Main page - https://neolelya.github.io/cinemaaddict-react-version/ * Statistics page
Python
UTF-8
2,939
3.609375
4
[ "MIT" ]
permissive
import pygame class Tile(object): snake_head = 0 snake_body = 1 snake_bend_left = 2 snake_bend_right = 3 snake_tail = 4 apple = 5 def __init__(self, cell_width, cell_height): self.filename = "../data/snake.png" self.columns = 5 self.rows = 4 self.image = pygame.transform.scale( pygame.image.load(self.filename), (int(cell_width * self.columns), int(cell_height * self.rows)), ).convert() self.tile_table = self.__build_index() """ Head Body Left Right Tail """ self.snake_left = ((3, 1), (1, 0), (0, 0), (0, 1), (3, 3)) self.snake_right = ((4, 0), (1, 0), (2, 2), (2, 0), (4, 2)) self.snake_up = ((3, 0), (2, 1), (2, 0), (0, 0), (3, 2)) self.snake_down = ((4, 1), (2, 1), (0, 1), (2, 2), (4, 3)) self.apple_pos = (0, 3) def __build_index(self): image_width, image_height = self.image.get_size() tile_width = image_width // self.columns tile_height = image_height // self.rows tile_table = [] for tile_x in range(self.columns): line = [] for tile_y in range(self.rows): rect = ( tile_x * tile_width, tile_y * tile_height, tile_width, tile_height, ) row = self.image.subsurface(rect) line.append(row) tile_table.append(line) return tile_table def get_direction(self, direction): if direction == pygame.K_LEFT: return self.snake_left elif direction == pygame.K_RIGHT: return self.snake_right elif direction == pygame.K_UP: return self.snake_up elif direction == pygame.K_DOWN: return self.snake_down else: raise RuntimeError("Invalid direction") def get_tile_for(self, part, direction): snake_parts = self.get_direction(direction) body_part = snake_parts[part] col, row = body_part[0], body_part[1] return self.tile_table[col][row] def get_head(self, direction) -> pygame.Surface: return self.get_tile_for(Tile.snake_head, direction) def get_body(self, direction) -> pygame.Surface: return self.get_tile_for(Tile.snake_body, direction) def get_bend_left(self, direction) -> pygame.Surface: return self.get_tile_for(Tile.snake_bend_left, direction) def get_bend_right(self, direction) -> pygame.Surface: return self.get_tile_for(Tile.snake_bend_right, direction) def get_tail(self, direction) -> pygame.Surface: return self.get_tile_for(Tile.snake_tail, direction) def get_apple(self) -> pygame.Surface: col = self.apple_pos[0] row = self.apple_pos[1] return self.tile_table[col][row]
Go
UTF-8
1,746
3.078125
3
[ "Apache-2.0" ]
permissive
package model import ( "bytes" "fmt" "strings" ) func (s *Service) translatePorts() { for _, c := range s.Containers { if c == nil { // TODO: catch this earlier continue } ports := []string{} if c.Ports != nil { for _, p := range c.Ports { parts := strings.SplitN(p, ":", 4) if len(parts) == 4 { ports = append(ports, parts[3]) } else { ports = append(ports, p) } } } c.Ports = ports if c.Ingress != nil { for _, i := range c.Ingress { if i.Host == "" { i.Host = s.Name } if i.Path == "" { i.Path = "/" } } } } } func (s *Service) translateVolumes() { for vName, v := range s.Volumes { if v == nil { v = &Volume{} s.Volumes[vName] = v } v.Name = vName if v.Persistent && v.Size == "" { v.Size = "20Gi" } } } //MarshalYAML serializes e into a YAML document. The return value is a string; It will fail if e has an empty name. func (e *EnvVar) MarshalYAML() (interface{}, error) { if e.Name == "" { return "", fmt.Errorf("missing values") } var buffer bytes.Buffer buffer.WriteString(e.Name) buffer.WriteString("=") if e.Value != "" { buffer.WriteString(e.Value) } return buffer.String(), nil } //UnmarshalYAML parses the yaml element and sets the values of e; it will return an error if the parsing fails, or //if the format is incorrect func (e *EnvVar) UnmarshalYAML(unmarshal func(interface{}) error) error { var envvar string if err := unmarshal(&envvar); err != nil { return err } envvar = strings.TrimPrefix(envvar, "=") parts := strings.SplitN(envvar, "=", 2) if len(parts) != 2 { return fmt.Errorf("Invalid environment variable syntax") } e.Name = parts[0] e.Value = parts[1] return nil }
Java
UTF-8
9,531
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package trabalho.poo.wm; import java.util.ArrayList; /** * * @author wilsonmielke */ public interface VendController extends Usefull{ public static void outArrayVend(ArrayList<Vendedor> a){ for(int i = 0; i<a.size(); i++){ System.out.println("("+i+") - "+a.get(i).getNome()); } System.out.println("("+a.size()+") - Voltar"); } public static void firstLoginVend(ArrayList acc){ if(acc.isEmpty()){ System.out.println("Nenhuma conta vendedor detectada, gerando uma nova"); cadVend(acc); } } public static int LoginVendor(int usertype, ArrayList<Vendedor> acc,ArrayList Ses){ System.out.println("Escolha a conta:"); if(acc.isEmpty()){ firstLoginVend(acc); } System.out.println("Escolha a conta:"); outArrayVend(acc); int ind = s.nextInt(); if(ind==acc.size())return usertype = -1; System.out.println("Entre com a senha:\n"); String pass = s.next(); if(acc.get(ind).Auth(pass)){ System.out.println("Acesso permitido!"); Ses.clear(); Ses.add("User: vendedor"); Ses.add(acc.get(ind).getNome()); Ses.add(acc.get(ind)); return usertype = 1; }else{ System.out.println("Senha incorreta!"); return usertype = -1; } } public static void cadVend(ArrayList acc){ System.out.println("Entre com os seguintes dados:"); System.out.println("Nome:"); String n1 = s.next(); System.out.println("Sobrenome:"); String sn = s.next(); System.out.println("Data de nascimento:"); String bd = s.next(); System.out.println("Telefone"); String t1 = s.next(); System.out.println("CPF:"); String cpf = s.next(); System.err.println("Cidade:"); String c1 = s.next(); System.out.println("Estado:"); String es = s.next(); System.out.println("País:"); String pa = s.next(); System.out.println("Endereço:"); String end = s.next(); System.out.println("Número:"); int num = s.nextInt(); System.err.println("login:"); String l1 = s.next(); System.err.println("Senha:"); String s1 = s.next(); Vendedor vend1 = new Vendedor(n1,sn,bd,t1,cpf,c1,es,pa,end,num,DateAndTime.DateTime(),l1,s1,acc); System.out.println("Usuário cadastrado com sucesso!"); } public static void editVend(ArrayList<Vendedor> acc,int ut){ if(ut==2 || ut==1){ System.out.println("Escolha o registro que deseja alterar"); outArrayVend(acc); int ind = s.nextInt(); if(ind==acc.size())return; System.out.println("Qual campo deseja editar?"); getVendData(acc.get(ind)); System.out.println("(12)Senha"); int d = s.nextInt(); switch (d){ case 1: System.out.println("Novo Nome:"); String t = s.next(); if(t.equals(acc.get(ind).getNome())){ System.out.println("Nome igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setNome(t); System.out.println("Campo alterado com sucesso!"); break; case 2: System.out.println("Nova Data de nascimento:"); t = s.next(); if(t.equals(acc.get(ind).getNasc())){ System.out.println("Data de nascimento igual a anterior!"); editVend(acc,ut); } acc.get(ind).setDataNasc(t); System.out.println("Campo alterado com sucesso!"); break; case 3: System.out.println("Novo Sobrenome:"); t = s.next(); if(t.equals(acc.get(ind).getSobre())){ System.out.println("Sobrenome igual a anterior!"); editVend(acc,ut); } acc.get(ind).setSobrenome(t); System.out.println("Campo alterado com sucesso!"); break; case 4: System.out.println("Novo Telefone:"); t = s.next(); if(t.equals(acc.get(ind).getPhone())){ System.out.println("Telefone igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setPhone(t); System.out.println("Campo alterado com sucesso!"); break; case 5: System.out.println("Novo CPF:"); t = s.next(); if(t.equals(acc.get(ind).getCPF())){ System.out.println("CPF igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setCPF(t); System.out.println("Campo alterado com sucesso!"); break; case 6: System.out.println("Nova Cidade:"); t = s.next(); if(t.equals(acc.get(ind).getCid())){ System.out.println("Cidade igual a anterior!"); editVend(acc,ut); } acc.get(ind).setCidade(t); System.out.println("Campo alterado com sucesso!"); break; case 7: System.out.println("Novo Estado:"); t = s.next(); if(t.equals(acc.get(ind).getEst())){ System.out.println("Estado igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setEstado(t); System.out.println("Campo alterado com sucesso!"); break; case 8: System.out.println("Novo País:"); t = s.next(); if(t.equals(acc.get(ind).getPais())){ System.out.println("País igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setPais(t); System.out.println("Campo alterado com sucesso!"); break; case 9: System.out.println("Novo Endereço:"); t = s.next(); if(t.equals(acc.get(ind).getEnd())){ System.out.println("Endereço igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setEndereco(t); System.out.println("Campo alterado com sucesso!"); break; case 10: System.out.println("Novo Número:"); int i = s.nextInt(); if(i==acc.get(ind).getNumero()){ System.out.println("Numero igual ao anterior!"); editVend(acc,ut); } acc.get(ind).setNumero(i); System.out.println("Campo alterado com sucesso!"); break; case 12: acc.get(ind).changePass(); } //acc.remove(ind); //cadVend(acc); } } public static void eraseVend(ArrayList<Vendedor> acc,int usertype, int uo){ System.out.println("Escolha o registro a ser apagado:"); outArrayVend(acc); int ind = s.nextInt(); if(ind==acc.size())return; acc.remove(ind); System.out.println("Registro apagado com sucesso!"); } public static void getVendData(Vendedor vend){ System.out.println("Dados da conta:" + "\n(1)Nome:"+vend.getNome() + "\n(2)Data de Nascimento:"+vend.getNasc() + "\n(3)Sobrenome:"+vend.getSobre() + "\n(4)Telefone:"+vend.getPhone() + "\n(5)CPF:"+vend.getCPF() + "\n(6)Cidade:"+vend.getCid() + "\n(7)Estado:"+vend.getEst() + "\n(8)País:"+vend.getPais() + "\n(9)Endereço:"+vend.getEnd() + "\n(10)Número:"+vend.getNumero() + "\n(11)Data de cadastro:"+vend.getCreate()); } }
Java
GB18030
5,953
2.8125
3
[]
no_license
package editor; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; /** * ClipPicӡɾƶij */ public class ClipPicUndoManager extends UndoManager { protected OneFrameDraw spriteManager; private int used; public ClipPicUndoManager(OneFrameDraw spriteManager) { this.spriteManager = spriteManager; used = 0; } public boolean addEdit(UndoableEdit anEdit) { if (used >= getLimit() - 10) { setLimit(getLimit() + 100); } ++used; return super.addEdit(anEdit); } public void addUndoSpriteAdd(ClipPic[] sprites) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicAdd(spriteManager, sprites)); } } } public void addUndoSpriteFlip(ClipPic[] sprites, int type) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicFlip(spriteManager, sprites, type)); } } } public void addUndoSpriteMove(ClipPic[] sprites, int offsetX, int offsetY) { if ((offsetX != 0 || offsetY != 0) && sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicMove(spriteManager, sprites, offsetX, offsetY)); } } } public void addUndoSpriteRemove(ClipPic[] sprites) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicRemove(spriteManager, sprites)); } } } public void addUndoSpriteScale(ClipPic[] sprites, double offsetScale) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicScale(spriteManager, sprites, offsetScale)); } } } public void addUndoSpriteAngle(ClipPic[] sprites, double offsetAngle) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicAngle(spriteManager, sprites, offsetAngle)); } } } public void addUndoSpriteAlpha(ClipPic[] sprites, double offsetAlpha) { if (sprites != null) { if (sprites.length > 0) { addEdit(new UndoClipPicAlpha(spriteManager, sprites, offsetAlpha)); } } } public int getUsedId() { return used; } public void redo() { try { if (canRedo()) { super.redo(); ++used; // System.out.println("redo: "+used); } } catch (Exception e) { e.printStackTrace(); } } public void undo() { try { if (canUndo()) { super.undo(); --used; // System.out.println("undo: "+used); } } catch (Exception e) { e.printStackTrace(); } } } class UndoClipPicAdd extends AbstractUndoableEdit { private ClipPic[] sprites; private OneFrameDraw spriteManager; public UndoClipPicAdd(OneFrameDraw spriteManager, ClipPic[] sprites) { this.spriteManager = spriteManager; this.sprites = sprites; } public void redo() { super.redo(); spriteManager.redoAdd(sprites); } public void undo() { super.undo(); spriteManager.undoAdd(sprites); } } class UndoClipPicFlip extends AbstractUndoableEdit { private OneFrameDraw spriteManager; private ClipPic[] sprites; private int type; public UndoClipPicFlip(OneFrameDraw spriteManager, ClipPic[] sprites, int type) { this.spriteManager = spriteManager; this.sprites = sprites; this.type = type; } public void redo() { super.redo(); spriteManager.flipSprites(sprites, type); } public void undo() { super.undo(); spriteManager.flipSprites(sprites, type); } } class UndoClipPicMove extends AbstractUndoableEdit { private OneFrameDraw spriteManager; private ClipPic[] sprites; int offsetX, offsetY; public UndoClipPicMove(OneFrameDraw spriteManager, ClipPic[] sprites, int offsetX, int offsetY) { this.spriteManager = spriteManager; this.sprites = sprites; this.offsetX = offsetX; this.offsetY = offsetY; } public void redo() { super.redo(); spriteManager.redoMove(sprites, offsetX, offsetY); } public void undo() { super.undo(); spriteManager.undoMove(sprites, offsetX, offsetY); } } class UndoClipPicRemove extends AbstractUndoableEdit { private ClipPic[] sprites; private OneFrameDraw spriteManager; public UndoClipPicRemove(OneFrameDraw spriteManager, ClipPic[] sprites) { this.spriteManager = spriteManager; this.sprites = sprites; } public void redo() { super.redo(); spriteManager.redoRemove(sprites); } public void undo() { super.undo(); spriteManager.undoRemove(sprites); } } class UndoClipPicScale extends AbstractUndoableEdit { private ClipPic[] sprites; private OneFrameDraw spriteManager; private double offsetScale; public UndoClipPicScale(OneFrameDraw spriteManager, ClipPic[] sprites, double offsetScale) { this.spriteManager = spriteManager; this.sprites = sprites; this.offsetScale = offsetScale; } public void redo() { super.redo(); spriteManager.scaleSprites(sprites, offsetScale); } public void undo() { super.undo(); spriteManager.scaleSprites(sprites, -offsetScale); } } class UndoClipPicAngle extends AbstractUndoableEdit { private ClipPic[] sprites; private OneFrameDraw spriteManager; private double offsetAngle; public UndoClipPicAngle(OneFrameDraw spriteManager, ClipPic[] sprites, double offsetAngle) { this.spriteManager = spriteManager; this.sprites = sprites; this.offsetAngle = offsetAngle; } public void redo() { super.redo(); spriteManager.angleSprites(sprites, offsetAngle); } public void undo() { super.undo(); spriteManager.angleSprites(sprites, -offsetAngle); } } class UndoClipPicAlpha extends AbstractUndoableEdit { private ClipPic[] sprites; private OneFrameDraw spriteManager; private double offsetAlpha; public UndoClipPicAlpha(OneFrameDraw spriteManager, ClipPic[] sprites, double offsetAlpha) { this.spriteManager = spriteManager; this.sprites = sprites; this.offsetAlpha = offsetAlpha; } public void redo() { super.redo(); spriteManager.alphaSprites(sprites, offsetAlpha); } public void undo() { super.undo(); spriteManager.alphaSprites(sprites, -offsetAlpha); } }
C#
UTF-8
2,773
2.703125
3
[]
no_license
namespace CompanySampleDataImporter.Importer.Importers { using System; using System.Collections.Generic; using CompanySampleDataImporter.Importer.Importers.Contracts; using CompanySampleDataImporter.Data; using System.IO; using System.Linq; public class ManagersImporter : IImporter { public string Message { get { return "Importing manager id(s)"; } } public int Order { get { return 3; } } public Action<CompanyEntities, TextWriter> Get { get { return (db, tr) => { // levelsSum == 100 => true var levels = new[] { 5, 5, 10, 10, 10, 15, 15, 15, 15 }; // Returns all ids in random order var allEmpoyeeIds = db .Employees .OrderBy(e => Guid.NewGuid()) .Select(e => e.Id) .ToList(); var currentPercentage = 0; List<int> previousManagers = null; foreach (var level in levels) { var skip = (int)((currentPercentage * allEmpoyeeIds.Count) / 100.0); var take = (int)((level * allEmpoyeeIds.Count) / 100.0); var currentEmployeeIds = allEmpoyeeIds .Skip(skip) .Take(take) .ToList(); var employees = db .Employees .Where(e => currentEmployeeIds.Contains(e.Id)) .ToList(); foreach (var employee in employees) { employee.ManagerId = previousManagers == null ? null : (int?)previousManagers[ RandomGenerator.GetRandomNumber(0, previousManagers.Count - 1)]; } tr.Write("."); db.SaveChanges(); db.Dispose(); db = new CompanyEntities(); previousManagers = currentEmployeeIds; currentPercentage += level; } }; } } } }
Java
UTF-8
2,643
2.359375
2
[]
no_license
package russo.it.newapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; public class SplashScreen extends Activity{ ImageView logo; Animation animFadeIn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); View decorView = getWindow().getDecorView(); // Hide both the navigation bar and the status bar. // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as // a general rule, you should design your app to hide the status bar whenever you // hide the navigation bar. int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); logo=(ImageView)findViewById(R.id.img_splash); animFadeIn= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in); logo.startAnimation(animFadeIn); //*---Thread---*/// Thread threadLanciatore=new Thread(){ public void run(){ try { int tempo=0; while (tempo<6000){ sleep(100); tempo += 100; } Intent intent = new Intent(getApplicationContext(),MainActivity.class); //intent.setClassName("russo.it.myappdrusso","russo.it.myappdrusso.HomePage"); startActivity(intent); } catch (InterruptedException exc){ exc.printStackTrace(); } finally { finish(); } } }; threadLanciatore.start(); } @Override protected void onResume() { super.onResume(); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); } // public void goHomePage(View view) { // //Intent esplicito // //Intent intent = new Intent(this, HomePage.class); // //startActivity(intent); // Intent intent = new Intent(); // // intent.setClassName("russo.it.myappdrusso","russo.it.myappdrusso.HomePage"); // startActivity(intent); // } }
Java
ISO-8859-1
4,717
2.15625
2
[]
no_license
package com.cliente.view; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Toast; import com.cliente.controller.CadastroController; import com.cliente.dao.LogadoSing; import com.cliente.pojo.Cliente; import com.view.garcom.R; public class AlterarDadosActivity extends Activity { OnDateSetListener datePickerListener; int year; int monthOfYear; int dayOfMonth; int hour; int minute; Intent intent; private EditText editTextNomeCompleto; private EditText editTextCpf; private Button editTextDataNascimento; private EditText editTextCelular; private EditText editTextEmail; private EditText editTextSenha; private EditText editTextConfirmarSenha; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_alterar_dados); editTextNomeCompleto = (EditText) findViewById(R.id.editTextNomeCompleto); editTextCpf = (EditText) findViewById(R.id.editTextCpf); editTextDataNascimento = (Button) findViewById(R.id.editTextDataNascimento); editTextCelular = (EditText) findViewById(R.id.editTextCelular); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextSenha = (EditText) findViewById(R.id.editTextSenha); editTextConfirmarSenha = (EditText) findViewById(R.id.editTextConfirmarSenha); editTextNomeCompleto.setText(LogadoSing.getInst().getCliente() .getNmPessoa()); editTextCpf.setText(LogadoSing.getInst().getCliente().getNrCpf()); editTextDataNascimento.setText(LogadoSing.getInst().getCliente() .getDtNascimento()); editTextCelular.setText(LogadoSing.getInst().getCliente() .getNrCelular()); editTextEmail.setText(LogadoSing.getInst().getCliente().getDsEmail()); editTextSenha.setText(LogadoSing.getInst().getCliente().getDsSenha()); datePickerListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int selectedYear, int selectedMonthOfYear, int selectedDayOfMonth) { year = selectedYear; monthOfYear = selectedMonthOfYear; dayOfMonth = selectedDayOfMonth; editTextDataNascimento.setText(new StringBuilder() .append(String.format("%02d", dayOfMonth)).append("/") .append(String.format("%02d", monthOfYear + 1)) .append("/").append(String.format("%04d", year))); } }; } public void editTextData(View view) { final Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(this, datePickerListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); } public void onClickCancelar(View view){ finish(); } public void onClickContinuar(View view) { String msg = null; String nomeCompleto = String.valueOf(editTextNomeCompleto.getText()); String cpf = String.valueOf(editTextCpf.getText()); String dataNascimento = String .valueOf(editTextDataNascimento.getText()); String celular = String.valueOf(editTextCelular.getText()); String email = String.valueOf(editTextEmail.getText()); String senha = String.valueOf(editTextSenha.getText()); String confirmarSenha = String .valueOf(editTextConfirmarSenha.getText()); Cliente cliente = new Cliente(); cliente.setNmPessoa(nomeCompleto); cliente.setNrCpf(cpf); cliente.setDtNascimento(dataNascimento); cliente.setNrCelular(celular); cliente.setDsEmail(email); cliente.setDsSenha(senha); cliente.setIeAtivo(true); try { if(senha.equals(confirmarSenha)){ Cliente cliente2 = new Cliente(); cliente2 = CadastroController.salvar(cliente); Toast.makeText(getApplicationContext(), "Dados Alterados!", Toast.LENGTH_LONG); if (cliente2 != null) { if (cliente2.getNrCpf() != null) { LogadoSing.getInst().setCliente(cliente2); Intent intent = new Intent(this, MenuActivity.class); this.startActivity(intent); finish(); } } else { msg = "As senhas informadas no so iguais!"; Toast msgs = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG); msgs.show(); editTextSenha.setFocusable(true); } } } catch (Exception e) { msg = e.getMessage(); Toast msgs = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG); msgs.show(); } } }
Python
UTF-8
1,954
3.4375
3
[]
no_license
#!/usr/bin/env python3 from math import cos, pi #Retrourne une valeur pseudo aléatoire entre 0 et 1 def noise(var): var = (var<<13)^var return (((var * (var * var * 15731 + 789221) + 1376312589) & 0xfffffff) / 2147483648.0) #Retourne un vecteur représentant une matrice 3D avec tous les bruits def noise2D(x,y): return noise(int(noise(x) * 90000+y))#Multiplication pour aggrandir les ecarts #Interpolation par cosinus pour obtenir des courbes arrondies #TODO:Remplacer cosin interp par cubic interp def interpolate(a, b, time): return (1. - time) * a + time * b; def smoothNoise(x): if x >= 0: intX = int(x) else: intX = int(x) - 1 fracX = x-intX return interpolate(noise(intX),noise(intX+1),fracX) def smoothNoise2D(x,y): if x >= 0: intX = int(x); else: intX = int(x) - 1; if y >= 0: intY = int(y); else: intY = int(y) - 1; fracX = x-intX fracY = y-intY A = noise2D(intX,intY) B = noise2D(intX+1,intY) C = noise2D(intX,intY+1) interX = interpolate(A,B,fracX) interY = interpolate(A,C,fracX) return interpolate(interX,interY, fracY) #nOctaves : nombre d'appel a smoothNoise #freq: "Force" du premier appel #Persist: modif freq a chaque appel def perlinNoise2D(nOctaves, freq, persist, x, y): amplitude = 1 curFreq = freq var = 0 for i in range(nOctaves): var += smoothNoise2D(int(x * curFreq) + i * 4096, int(y * curFreq)+ i * 4096) # Addition pour translater le centre du motif amplitude = amplitude * persist curFreq = curFreq*2 return var * (1 - persist)/(1-amplitude) def perlinText(height, width): tex = [] for i in range(height): row = [] for j in range(width): color = perlinNoise2D(10,1000,0.47,i,j)*255 row.append([color, color+20, color]) tex.append(row) return tex #print(perlinText(10,10))
JavaScript
UTF-8
3,457
2.8125
3
[]
no_license
/*-----Author:Tejashree Prabhu----References:CS546 Lecture 6 Codebase, CS546 Lecture 10 Codebase,stackoverflow-----*/ const express = require("express"); const router = express.Router(); const data = require("../data"); const moviesData = data.movies; const commentsData = data.comments; router.get("/", (req, res) => { var skip = req.query.skip; var take = req.query.take; if(skip == undefined || skip < 0){ skip = 0; } if(take == undefined || take < 0){ take = 20; }else if(take>100){ take = 100; } skip = parseInt(skip); take = parseInt(take); moviesData.getAllMovies(skip, take).then((moviesList) => { res.status(200).json(moviesList); }).catch((e) => { res.status(500).json({ error: e }); }); }); router.get("/:id", (req, res) => { moviesData.getMoviesById(req.params.id).then((movie) => { res.json(movie); }).catch(() => { res.status(404).json({ error: "Movie not found " }); }); }); router.post("/", (req, res) => { let moviePostData = req.body; moviesData.addMovie(moviePostData.title, moviePostData.cast[0].firstName, moviePostData.cast[0].lastName, moviePostData.info.director, moviePostData.info.yearReleased, moviePostData.plot, moviePostData.rating ) .then((newMovie) => { res.json(newMovie); }).catch((e) => { res.status(500).json({ error: e }); }); }); router.put("/:id", (req, res) => { let moviePostData = req.body; let getMovies = moviesData.getMoviesById(req.params.id); getMovies.then(() => { return moviesData.updateMovie(req.params.id, moviePostData.title,moviePostData.cast[0].firstName, moviePostData.cast[0].lastName, moviePostData.info.director, moviePostData.info.yearReleased, moviePostData.plot, moviePostData.rating) .then((updatedMovies) => { res.json(updatedMovies); }).catch((e) => { res.status(500).json({ error: e }); }); }).catch((e) => { res.status(404).json({ error: e }); }); }); router.patch("/:id", (req, res) => { let moviePostData = req.body; let getMovies = moviesData.getMoviesById(req.params.id); getMovies.then(() => { return moviesData.patchMovie(req.params.id, moviePostData) .then((updatedMovies) => { res.json(updatedMovies); }).catch((e) => { res.status(500).json({ error: e }); }); }).catch((e) => { res.status(404).json({ error: e }); }); }); router.post("/:id/comments", (req, res) => { let commentPostData = req.body; commentsData.addComment(req.params.id, commentPostData.name, commentPostData.comment) .then((newComment) => { res.json(newComment); }).catch((e) => { res.status(500).json({ error: e }); }); }); router.delete("/:taskId/:commentId", (req, res) => { let getComment = commentsData.getCommentById(req.params.commentId); getComment.then((comment) => { return commentsData.removeComment(req.params.taskId,comment) .then(() => { res.status(200).json({"result":"ok"}); }).catch((e) => { res.status(500).json({ error: e }); }); }).catch(() => { res.status(404).json({ error: "comment not found" }); }); }); module.exports = router;
Java
UTF-8
1,021
2.46875
2
[]
no_license
package type; import input.Input; import java.awt.Color; import java.awt.Graphics; import java.io.Serializable; public abstract class Flag implements Serializable{ private static final long serialVersionUID = 7414458948479691583L; /*private List<Flag> internal; public Flag(){ internal = new ArrayList<Flag>(); } public void add(Flag flag){ internal.add(flag); } public void remove(Flag flag){ internal.remove(flag); } public List<Flag> get(){ return internal; } public Flag getAt(int index){ return internal.get(index); }*/ @Override public String toString(){ return this.getClass().getSimpleName(); } public abstract void draw(int x, int y, int size, Graphics buffer); public abstract Color getColor(); public boolean onAdd(Map map, Input i) { return true; } public boolean useInput(){ return false; } public abstract void update(); public abstract boolean blocked(Map map); public abstract boolean override(); public abstract float getCost(); }
C#
UTF-8
2,208
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using ZedGraph; namespace PlotComPlus.Gui { /// <summary> /// Represents the popup window which contains a graph control /// that a user can interact (zoom, save) with. /// </summary> partial class Form1 : Form { /// <summary> /// The constructor. /// </summary> /// <param name="plotter">Plotter draws graph.</param> /// <param name="processes">Processes to be shown.</param> public Form1(GraphPlotter plotter, List<Process> processes) { InitializeComponent(); _plotter = plotter; _processes = processes; } private void Form1_Load(object sender, EventArgs e) { MasterPane master = zgc.MasterPane; master = _plotter.Plot(master, _processes); zgc.AxisChange(); zgc.IsShowPointValues = true; using (Graphics g = this.CreateGraphics()) { // Align all mini-graphs to single column. master.SetLayout(g, PaneLayout.SingleColumn); // Set the ticks/scale to a sensible value automatically. foreach (GraphPane pane in master.PaneList) { pane.XAxis.ResetAutoScale(pane, g); pane.YAxis.ResetAutoScale(pane, g); } } this.ResetGraphSize(); } private void Form1_Resize(object sender, EventArgs e) { this.ResetGraphSize(); } /// <summary> /// This allow the control to be resized with the /// pop up window. /// </summary> private void ResetGraphSize() { zgc.Location = new Point(10, 10); // Leave a small margin around // the outside of the control. zgc.Size = new Size(ClientRectangle.Width - 20, ClientRectangle.Height - 20); } private GraphPlotter _plotter; private List<Process> _processes; } }
Java
UTF-8
621
3.4375
3
[]
no_license
package j47_ioadvance; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferReaderDemo { public static void main(String [] args) throws IOException { //System.in是inputStream类对象 //BufferedReader构造方法需要接收reader类对象 //InputStreamReader将字节流变为字符流 BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入数据:"); String str = buf.readLine(); //以回车为换行 System.out.println("输入内容:"+str); } }
JavaScript
UTF-8
4,565
3.03125
3
[ "MIT" ]
permissive
var tagInput=document.getElementById("tag-name"); var addTagButton=document.getElementById("add-tag"); var tagList=document.getElementById("tag-list"); var createNewTag=function(tagvalue){ var listItem=document.createElement("li"); var tagsCount=tagList.childElementCount console.log('tags count ', tagsCount) listItem.id="tag-"+(tagsCount+1); var listLabel=document.createElement("label"); var individualTagCloseButton=document.createElement("button"); listLabel.innerText=tagvalue; individualTagCloseButton.class="tagButton"; individualTagCloseButton.id="tagclose-"+(tagsCount+1); individualTagCloseButton.innerText="x"; individualTagCloseButton.onclick=removeTag; listItem.appendChild(listLabel); listItem.appendChild(individualTagCloseButton); console.log('appendChild ', listItem) return listItem } var addTag=function(){ console.log('Add Tag'); var listItem=createNewTag(tagInput.value); tagInput.value=""; tagList.appendChild(listItem); } var removeTag=function(index){ console.log('index ', index.path[1].id) var element = document.getElementById(index.path[1].id); element.parentNode.removeChild(element); element[index].removeChild(element[index]); } addTagButton.onclick=addTag; var taskInput=document.getElementById("task-name"); var statusInput=document.getElementById("status-type"); var addTaskButton=document.getElementById("add-task"); var todoTable=document.getElementById('todo-table'); var createNewTag=function(tagvalue){ var listItem=document.createElement("li"); var tagsCount=tagList.childElementCount console.log('tags count ', tagsCount) listItem.id="tag-"+(tagsCount+1); var listLabel=document.createElement("label"); var individualTagCloseButton=document.createElement("button"); listLabel.innerText=tagvalue; individualTagCloseButton.class="tagButton"; individualTagCloseButton.id="tagclose-"+(tagsCount+1); individualTagCloseButton.innerText="x"; individualTagCloseButton.onclick=removeTag; listItem.appendChild(listLabel); listItem.appendChild(individualTagCloseButton); console.log('appendChild ', listItem) return listItem } var addTask=function(){ console.log('Add Tag'); var taskName=taskInput.value; var statusName=statusInput; var tableBody=todoTable.children console.log('tablebody ', tableBody[0].childElementCount) var todosCount=tableBody[0].childElementCount console.log('todoElement Table ', todoTable) console.log('todos count ',taskName, statusName, todosCount) var todoItem=document.createElement("tr"); todoItem.id="todo-"+(todosCount); var td1=document.createElement("td"); td1.id="td-1"; td1.align="center"; var checkb=document.createElement("input"); checkb.type="checkbox"; checkb.id="todoItem-"+(todosCount); td1.appendChild(checkb) var td2=document.createElement("td"); td1.id="td-2"; td2.align="center"; var taskLabel=document.createElement("label"); taskLabel.id="todoItemName-"+(todosCount); taskLabel.innerText=taskName; td2.appendChild(taskLabel); var td3=document.createElement("td"); td3.id="td-3"; td3.class="todoListTags"; td3.align="center"; var tasksUL=document.createElement("ul"); tasksUL.align="center"; tasksUL.class="todoTagsList"; tasksUL.id="todoItemTags-"+(todosCount); console.log("uL ", tagList.children); for(let i=0;i<tagList.children.length;i++) { var liItem = tagList.children[i]; liItem.id=""; tasksUL.appendChild(liItem.children[0]); } td3.appendChild(tasksUL); var td4=document.createElement("td"); td4.id="td-4"; td4.align="center"; var statusLabel=document.createElement("label"); statusLabel.id="todoItemStatus-"+(todosCount); statusLabel.innerText="Completed"; td4.appendChild(statusLabel); var td5=document.createElement("td"); td5.id="td-5"; td5.align="center"; var editButton=document.createElement("button"); editButton.id="edittr-"+(todosCount); editButton.class="todoEdit"; editButton.innerText="Edit"; var deleteButton=document.createElement("button"); deleteButton.id="deletetr-"+(todosCount); deleteButton.class="todoDelete"; deleteButton.innerText="Delete"; td5.appendChild(editButton); td5.appendChild(deleteButton); todoItem.appendChild(td1); todoItem.appendChild(td2); todoItem.appendChild(td3); todoItem.appendChild(td4); todoItem.appendChild(td5); tableBody[0].appendChild(todoItem); } addTaskButton.onclick=addTask; var removeTask=function(index){ console.log('index ', index.path[1].id) var element = document.getElementById(index.path[1].id); element.parentNode.removeChild(element); element[index].removeChild(element[index]); }
C
UTF-8
823
2.71875
3
[]
no_license
#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<netinet/in.h> #include<netinet/ip.h> struct st{ int op[10]; }v2; main(int argc,char**argv){ int len,sfd,nsfd,i,j; struct sockaddr_in v,v1; sfd=socket(AF_INET,SOCK_STREAM,0); if(sfd<0){ perror("SOCKET"); return; } perror("SOCKET"); v.sin_family=AF_INET; v.sin_port=htons(atoi(argv[1])); v.sin_addr.s_addr=inet_addr("0.0.0.0"); len=sizeof(v); bind(sfd,(struct sockaddr*)&v,len); perror("BIND:"); listen(sfd,5); perror("listen"); nsfd=accept(sfd,(struct sockaddr*)&v1,&len); perror("ACCEPT"); read(nsfd,&v2,sizeof(v2)); for(i=0;i<10-1;i++) for(j=0;j<10-i-1;j++){ if(v2.op[j]>v2.op[j+1]){ v2.op[j+1]=v2.op[j]+v2.op[j+1]-(v2.op[j]=v2.op[j+1]); } } for(i=0;i<10;i++) printf("%d ",v2.op[i]); }
Markdown
UTF-8
2,938
2.65625
3
[]
no_license
+++ title: "Chinese community must be vigilant to ensure that the Boards of Management furore is not a Barisan ‘smoke-screen’ to hide other provisions detrimental to Chinese education" date: "1990-05-20" tags: +++ _By Parliamentary Opposition Leader, DAP Secretary-General and MP for Tanjung, Lim Kit Siang, in Penang on Sunday, 20th May 1990:_ # Chinese community must be vigilant to ensure that the Boards of Management furore is not a Barisan ‘smoke-screen’ to hide other provisions detrimental to Chinese education The Chinese community and all concerned about mother-tongue education must be vigilant to ensure that the current furore over the Barisan Nasional’s proposal to abolish the Boards of Management of 432 ‘fully-aided’ Chinese primary schools is not a smokescreen to hide other provisions in the 1990 Education Bill which highly detrimental to Chinese education.</u> The Chinese educational bodies and the Chinese community must not fully focus on the Boards of Management issue, and allow other provisions which may be equally or even more damaging to Chinese education to be smuggled into the 1990 Education Bill. Is there an ulterior motive to keep Section 21(2) by engineering furore on abolition the Chinese Primary School Boards of Management? The Boards of Management furore, which was created by the announced of Deputy Education Minister, Woon See Chin, about its abolition in 432 Chinese primary schools, could be deliberately engineered to serve another ulterior purpose. This is to create the condition whereby the Chinese community are so afraid that the Boards of Management of the 432 ‘fully-assisted’ Chinese primary schools would be abolished that they would be prepared to agree to the ‘temporary’ existence of Section 21(2) of the 1961 Education Act. At the right time, a MCA or Gerakan ‘saviour’ will come out with a solution to overcome the imminent abolition of the Boards of Management of the 432 Chinese primary schools: the whole 1990 Education Bill will be deferred until the next general elections, including the repeal of Section 21(2) of the 1961 Education Act. The DAP will find such a ‘solution’ completely unacceptable. Tomorrow, the six-man Cabinet Committee on the 1990 Education Bill will meet for the fourth time. I call on the MCA, Gerakan and SUPP Ministers to present a common front tomorrow, and demand that the Education Minister, Anwar Ibrahim, should present two Education Bills in next month’s Parliament. The first Bill is to repeal Section 21(2) of the 1961 Education Act immediately, which is to take effect before the next general elections. The second Bill is to embody all the government’s proposals for the new Education Act for the 1990s, which should be tabled for first reading only. The public and all interested persons or organisations should be given at least six months to study and debate the new Education Act proposals.
Markdown
UTF-8
7,059
2.765625
3
[ "BSD-2-Clause" ]
permissive
# Access Access to service is granted after Agent receives notification of new channel was created for his offering: ```text event LogChannelCreated(address indexed _agent, address indexed _client, bytes32 indexed offering_hash, uint192 _deposit) ``` When Client receives same Ethereum event, he knows that he should shortly try to contact Agent and get `access message`. Client queries Agent for `access message`, providing `channel key` compliant with smart contract method: ```text function getKey(address _client_address, address _agent_address, uint32 _open_block_number, bytes32 _offering_hash) ``` Agent than retrieves `access message` from database and passed it to Client. `access message` is always encrypted using Client's public key, thus can be decrypted only by intended Client. Client's public key is reconstructed from `createChannel` Ethereum transaction. Access message \(aka endpoint message\) is created by Agent according to `access template`. `Access template` is agreed format for message, that contains all data needed to Client for this particular service. Access template shipped with `service plug-in`. Each `service plug-in` has unique access template. Both Agent and Client have identical access template, when choose to use same `service plug-in`. `Access template` - is JSON schema that includes: * `Access schema` - access fields to be filled by Agent * `Core fields` - fields that common for any service. They are required for proper `Privatix core` operation. They are generic and doesn't contain any service specifics. * `Service custom fields` - \(aka additional parameters\) any fields that needed for particular service operation. They do not processed by `Privatix core`, but passed to `Privatix adapter` for any custom logic. * `UI schema` - schema that can be used by GUI to display fields for best user experience \(currently not implemented\) Each `Access template` has unique hash. Any access message always includes in its body hash of corresponding `access template`. That's how access message is linked to template and related `service plug-in`. When Client receives access message, he checks that: * Access template with noted hash exists in Client's database * Access message passes validation according to access template Such validation ensures, that Agent and Client both has: * exactly same access template * access message is properly filled according to access template schema ## Access template schema example ```javascript { "title": "Privatix VPN access", "type": "object", "description": "Privatix VPN access template" "definitions": { "host": { "pattern": "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*:[0-9]{2,5}$", "type": "string" }, "simple_url": { "pattern": "^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?.+", "type": "string" }, "uuid": { "pattern": "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", "type": "string" } }, "properties": { "templateHash": { "title": "access tempate hash", "type": "string", "description": "Hash of this access template" }, "nonce": { "title": "nonce", "type": "string", "description": "uuid v4. Allows same access template to be shipped twice, resulting in unique access template offering hash." }, "username": { "$ref": "#/definitions/uuid" }, "password": { "type": "string", "description": "Can be used to transfer password" }, "paymentReceiverAddress": { "$ref": "#/definitions/simple_url", "description": "Address and port of agent's payment reciever endpoint" }, "serviceEndpointAddress": { "type": "string", "description": "(Optional) E.g. address of web service." }, "additionalParams": { "additionalProperties": { "type": "string" }, "minProperties": 1, "type": "object" } }, "required": [ "templateHash", "paymentReceiverAddress", "serviceEndpointAddress", "additionalParams" ] } ``` `additionalProperties` parameter may contain any arbitrary data required to access the service or receive the product. **Examples** * `additionalProperties` may contain DNS name and credentials for some web service. It will be received by Client's adapter and used to connect to web-service and consume a service. * `additionalProperties` may contain geolocation of apartment with direction how to open it. Direction maybe seen via user interface and/or sent to e-mail. All automation is done by adapter. Adapter gets access message content and can process `additionalProperties` data for authentication, preparing necessary configuration, running additional processes. ## Access workflow After Agent receives event `LogChannelCreated` he should process order and give access to Client for a service. This can be handled by adapter making additional work. Finally, `access message` is generated in `Privatix core database` and ready to be passed to Client. 1. Client queries Agent for `access message` via one of `messaging transport` 2. access message received from Agent \(job `ClientAfterChannelCreate`\) 3. Then in job `AgentPreEndpointMsgCreate` a. Agent's signature verified b. Message payload is decrypted c. Matching access template is found in local database d. Access message is validated to comply with `access template schema` Access is granted and maybe consumed by Client. Usually processed by Client's adapter. ## Access message format | encrypted payload | signature | | :--- | :--- | ### Access message packaging 1. Fill endpoint template \(JSON\) 2. Encrypt message payload using ECIES Ethereum implementation [ecies.Encrypt\(\)](https://godoc.org/github.com/ethereum/go-ethereum/crypto/ecies#Encrypt) 3. Generate keccak-256 hash of encrypted message payload \(as raw bytes\) 4. Sign hash with private key using Ethereum crypto package `Sign()` function ## Access message hash Keccak-256 hash of access message is used to uniquely identify access message. Hash is performed on whole offering message \(already encrypted and signed\). ## Access message verification 1. Split message encrypted payload by removing last 64 bytes of message 2. Generate keccak-256 hash of message payload 3. Use Ethereum crypto package `SigToPub()` function to retrieve Agent's public key 4. Compare provided in offering Agent's public key to that from step \(3\) 5. Decrypt encrypted message payload using [ecies.Decrypt\(\)](https://godoc.org/github.com/ethereum/go-ethereum/crypto/ecies#PrivateKey.Decrypt) 6. Validate message payload to corresponding template JSON scheme
C#
UTF-8
619
2.578125
3
[]
no_license
using BattleShipLibrary.GameInit; using System; using System.Collections.Generic; using System.Text; using Xunit; // Pattern of unit tests: // Arrange, Act, Assert namespace BattleShip.Tests { public class GameInitTests { [Fact] public void PopulateShotsFired_ShouldReturnGridOfFalseBools() { // Arrange GameInit gameInit = new GameInit(); bool[,] expected = new bool[10, 10]; // Act bool[,] actual = gameInit.PopulateShotsFired(); // Assert Assert.Equal(expected, actual); } } }
Shell
UTF-8
2,340
3.796875
4
[ "BSD-3-Clause", "MIT" ]
permissive
#!/bin/bash # # Copyright(c) 2012-2021 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # # The line below specified that line under it should be used as the test's short description when launching test via run_tests script. # The text should not be longer than 80 chars - if it is, the script will strip addititonal characters # DESCRIPTION Check data integrity for every cache mode and cache line size # Standard beginning for every test - get the main tests directory and # link the cas_lib file for CAS API, then use "start_test $*" to pass params # and do other necessary checks and setup TESTS_DIR="$(dirname $0)/../" . $TESTS_DIR/cas_lib start_test $* # This is where the real test starts which fio &> /dev/null if [ $? -ne 0 ] ; then error "Fio not installed!" end_test $CAS_TEST_NOT_RUN fi # Use CACHE_DEVICE provided by configuration file and remove partitions from this device TARGET_DEVICE_OPTION="$CACHE_DEVICE" remove_partitions TARGET_DEVICE_OPTION="$CORE_DEVICE" remove_partitions # Create one primary partition (ID=1) of size 2000M on CACHE_DEVICE TARGET_DEVICE_OPTION="$CACHE_DEVICE" PARTITION_SIZE_OPTION="2000M" PARTITION_IDS_OPTION="1" make_primary_partitions TARGET_DEVICE_OPTION="$CORE_DEVICE" PARTITION_SIZE_OPTION="10000M" PARTITION_IDS_OPTION="1" make_primary_partitions IO_ENGINES="sync psync vsync pvsync pvsync2 libaio posixaio mmap" CACHE_MODES="wb pt wa wt wo" CACHE_LINE_SIZES="4 8 16 32 64" for mode in $CACHE_MODES; do for line_size in $CACHE_LINE_SIZES; do CACHE_ID_OPTION="1" CACHE_DEVICE_OPTION="${CACHE_DEVICE}-part1" \ CACHE_MODE_OPTION="$mode" CACHE_LINE_SIZE="$line_size" \ CACHE_FORCE_OPTION="yes" start_cache CACHE_ID_OPTION="1" CORE_DEVICE_OPTION="${CORE_DEVICE}-part1" add_core for engine in $IO_ENGINES; do run_cmd "fio --ioengine=${engine} --direct=1 --name=test \ --filename=${DEVICE_NAME}1-1 --bs=4k --iodepth=64 \ --readwrite=randrw --verify=crc32 --runtime=300 --time_based \ --size=10G" done CACHE_ID_OPTION="1" stop_cache done done # Always return 0 at the end of the test - if at any point something has failed # in the API functions, test will end and return a proper result. # If you need to check other things during the test and end the test earlier, you # should end the test using "end_test $retval" function end_test 0
C++
UTF-8
1,512
3.265625
3
[ "MIT" ]
permissive
#include <fstream> #include "../Algorithms/knapsack.hpp" int main() { std::vector<Product> prodAvailableM1; std::vector<Product> prodAvailableM2; int maxAvailableM1; int sackSizeM1; int maxAvailableM2; int sackSizeM2; int value; int weight; std::ifstream file; // Creates the items available for knapsack 1. file.open("../Instances/mochila01.txt"); if (file.is_open()) { file >> maxAvailableM1 >> sackSizeM1; for (int i = 0; i < maxAvailableM1; i++) { file >> weight >> value; prodAvailableM1.push_back((Product){ value, weight }); } file.close(); } else std::cout << "ERROR: Unable to open file" << std::endl; // Creates the items available for knapsack 2. file.open("../Instances/mochila02.txt"); if (file.is_open()) { file >> maxAvailableM2 >> sackSizeM2; for (int i = 0; i < maxAvailableM2; i++) { file >> weight >> value; prodAvailableM2.push_back((Product){ value, weight }); } file.close(); } else std::cout << "ERROR: Unable to open file" << std::endl; // Calculates the maximum value for both knapsacks. Knapsack* ks = new Knapsack(); std::cout << "Maximum Value Sack 1: "; ks->knapsack(sackSizeM1, maxAvailableM1, prodAvailableM1); std::cout << "Maximum Value Sack 2: "; ks->knapsack(sackSizeM2, maxAvailableM2, prodAvailableM2); delete ks; return 0; }
Markdown
UTF-8
991
2.578125
3
[ "MIT" ]
permissive
# Cards test task for SEMrush 😊 Created interface for adding/deleting/editing cards. ### Try it out: https://cards-test-task.firebaseapp.com ### Features 1. User can add cards via modal window 'Add new' button 2. Modal fields are validated 3. Image can be uploaded from PC or drag'n'drop 4. Cards data is kept in localStorage 5. If you turn on editing mode, you can edit or delete cards 6. Pagination (maximum 9 cards per page regardless of their size) 7. Mobile adaptivity ### Technology used - React - Redux - React router - Webpack4 - Jest + enzyme - Travis - Eslint, Stylelint - Firebase hosting ### Quick setup In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:8080](http://localhost:8080) to view it in the browser. ### `yarn test` Runs tests ### `yarn build` Builds the app for production to the `build` folder.<br /> ### `yarn lint_js` Lints `.js` files ### `yarn lint_css` Lints `.css` files
Python
UTF-8
271
2.78125
3
[]
no_license
n = int(input()) b = [] c = [] for i in map(int, input().split()): if i % 2 == 0: b.append(i) else: c.append(i) if len(b) < 2 and len(c) < 2: print('-1') else: b += [-1e18, -1e18] c += [-1e18, -1e18] b.sort() c.sort() print(max(b[-1] + b[-2], c[-1] + c[-2]))
C
UTF-8
747
4.25
4
[]
no_license
/** A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. **/ #include<stdio.h> int is_palindromic(unsigned int n); int main(int argc, char** argv) { unsigned int i,j,max = 0; for (i=100; i <= 999; i++) { for(j=100; j<=999; j++) { unsigned int p = i*j; if (is_palindromic(p) && p > max) { max = p; } } } printf("%u\n",max); return 0; } int is_palindromic(unsigned int n) { unsigned int reverse_number = 0, t=n; while (t) { reverse_number = 10*reverse_number + (t % 10); t /= 10; } return reverse_number == n; }
Swift
UTF-8
1,954
2.71875
3
[ "MIT" ]
permissive
// // JMExtension+Bundle.swift // JMEpubReader // // Created by JunMing on 2021/3/30. // import Foundation extension Bundle { /// 当前项目bundle static var bundle: Bundle { return Bundle(for: JMBookContrller.self) } /// 获取bundle中文件路径 static func path(resource: String, ofType: String) -> String? { return Bundle.bundle.path(forResource: resource, ofType: ofType) } /// Resours文件bundle static var resouseBundle: Bundle? { if let budl = Bundle.path(resource: "Resours", ofType: "bundle") { return Bundle(path: budl) }else { return nil } } // 类方法 class func localizedString(forKey key: String) -> String? { return self.localizedString(forKey: key, value: nil) } // 参数value为可选值,可以传值为nil。 class func localizedString(forKey key: String, value: String?) -> String? { var language = Locale.preferredLanguages.first // (iOS获取的语言字符串比较不稳定)目前框架只处理en、zh-Hans、zh-Hant三种情况,其他按照系统默认处理 if language?.hasPrefix("en") ?? false { language = "en" } else if language?.hasPrefix("zh") ?? false { language = "zh-Hans" } else { language = "en" } if let path = Bundle.path(resource: language!, ofType: "lproj") { let v = Bundle(path: path)?.localizedString(forKey: key, value: value, table: nil) return Bundle.main.localizedString(forKey: key, value: v, table: nil) }else { return nil } } // class func frameworkBundle() -> Bundle { // return Bundle(for: JMReadManager.self) // } // // class func path(resource: String, type: String) -> String? { // return frameworkBundle().path(forResource: resource, ofType: type) // } }
Python
UTF-8
508
3.671875
4
[]
no_license
""" Module to calculate prime numbers.""" import sys def find_nth_prime(n, primes=None): primes = primes or [2] test = primes[-1]+1 while len(primes)<n: for p in primes: if p**2>test: primes.append(test) break if test%p==0: break # special case if len(primes)==0: primes.append(test) test += 1 return primes if __name__=="__main__": print(find_nth_prime(int(sys.argv[0])))
Ruby
UTF-8
376
3.296875
3
[]
no_license
class Show def show_board(board) puts puts " 1 2 3" puts " -------------" puts " A | #{board[0]} | #{board[1]} | #{board[2]} |" puts " -------------" puts " B | #{board[3]} | #{board[4]} | #{board[5]} |" puts " -------------" puts " C | #{board[6]} | #{board[7]} | #{board[8]} |" puts " -------------" puts end end