Beispiel #1
0
int main(int argc, char** argv) {
	if (argc < 2) {
		printf("This program requires 1 argument: The path of the PHP file to parse.\n");
		return -1;
	}
	SampleObserver observer;
	pelet::ParserClass parser;
	parser.SetVersion(pelet::PHP_54);
	parser.SetClassObserver(&observer);
	parser.SetClassMemberObserver(&observer);
	parser.SetFunctionObserver(&observer);
	parser.SetVariableObserver(&observer);
	
	pelet::LintResultsClass results;
	bool parsed = parser.ScanFile(argv[1], results);
	if (parsed) {
		printf("Parsing complete.\n");
	}
	else {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Parse error: %S on line %d\n", results.Error.getTerminatedBuffer(), results.LineNumber);
		u_fclose(ufout);
	}
	
	// this is only used so that this program can be run through valgrind (memory leak
	// detector). In real-world usage, this include is not needed.
	u_cleanup();
	return 0;
}
Beispiel #2
0
	/**
	 * This method gets called when a trait use statement has been found
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the class that uses the trait
	 * @param className the fully qualified name of the class that uses the trait
	 * @param traitName the fully qualified name of the trait to be used 
	 */
	virtual void TraitUseFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& traitName) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Trait Usage Found in class %.*S in namespace %.*S. Trait Name %.*S \n", 
			className.length(), className.getBuffer(), 
			namespaceName.length(), namespaceName.getBuffer(),
			traitName.length(), traitName.getBuffer());
		u_fclose(ufout);
	}
Beispiel #3
0
	/**
	 * This method gets called when a class is found.
	 * 
	 * @param const UnicodeString& namespace the fully qualified "declared" namespace of the class that was found
	 * @param const UnicodeString& className the name of the class that was found
	 * @param const UnicodeString& signature the list of classes that the class inherits / implements in code format
	 *        for example "extends UserClass implements Runnable"
	 * @param const UnicodeString& comment PHPDoc attached to the class
	 * @param lineNumber the line number (1-based) that the class was found in
	 */
	virtual void ClassFound(const UnicodeString&  namespaceName, const UnicodeString& className, const UnicodeString& signature, 
		const UnicodeString& comment, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Class Found: %.*S in namespace %.*S on line %d \n", 
			className.length(), className.getBuffer(), 
			namespaceName.length(), namespaceName.getBuffer(),
			lineNumber);
		u_fclose(ufout);		
	}
Beispiel #4
0
	/**
	 * This method gets called when a define declaration is found.
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace name that the constant that was found
	 * @param const UnicodeString& variableName the name of the defined variable
	 * @param const UnicodeString& variableValue the variable value
	 * @param const UnicodeString& comment PHPDoc attached to the define
	 * @param lineNumber the line number (1-based) that the define was found in
	 */
	virtual void DefineDeclarationFound(const UnicodeString& namespaceName, const UnicodeString& variableName, const UnicodeString& variableValue, 
		const UnicodeString& comment, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Define Found: %.*S in namespace %.*S on line %d\n", 
			variableName.length(), variableName.getBuffer(), 
			namespaceName.length(), namespaceName.getBuffer(), 
			lineNumber);
		u_fclose(ufout);
	}
Beispiel #5
0
void t4p::TagCacheClass::Print() {
    UFILE* ufout = u_finit(stdout, NULL, NULL);
    u_fprintf(ufout, "Number of working caches: %d\n", WorkingCaches.size());
    u_fclose(ufout);
    std::map<wxString, t4p::WorkingCacheClass*>::const_iterator it = WorkingCaches.begin();
    for (; it != WorkingCaches.end(); ++it) {
        it->second->SymbolTable.Print();
    }
}
Beispiel #6
0
U_CAPI UFILE * U_EXPORT2
u_get_stdout()
{
    if (gStdOut == NULL) {
        gStdOut = u_finit(stdout, NULL, NULL);
        ucln_io_registerCleanup(UCLN_IO_PRINTF, &uprintf_cleanup);
    }
    return gStdOut;
}
Beispiel #7
0
	/** 
	 * Override this method to perform any custom logic when a variable assignment is found. Note that the same 
	 * variable may be assigned different values at different times within the same function.
	 * The symbol will be constructed in the following way:
	 *
	 * Example assignment:  $name = $this->getName()->toString();
	 *
	 * Variable: The variable's ChainList will contain the variable's name in index 0: "$name"
	 * ChainList: This is a list of  properties / methods
	 *            that were successively invoked.
	 *            In this example, the expression chain list will have 3 items in
	 *           the chain list "$this" "->getName()" and "->toString()".
	 *
	 * The variable itself may contain an array key in it; like so: $person['name'] = $this->getName()->toString();
	 * In this case, Variable ChainList will contain 1 item: "$name" and the Variable Array Key will contain "name"
	 * 
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the containing class / function.
	 * @param const UnicodeString& className class where the variable was found. may be empty is variable is scoped 
	 *        inside a function or is global.
	 * @param const UnicodeString& methodName function/method name where the variable was found. may be empty if 
	 *        variable is globally scoped.
	 * @param const VariableClass& variable the name of the variable that was found, along with any array keys that were used
	 *       in the left hand of the assignment. 
	 * @param const ExpressionClass& expression the expression assigned to the variable
	 * @param const UnicodeString& comment PHPDoc attached to the variable
	 * 
	 * @see pelet::VariableClass
	 */
	virtual void VariableFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& methodName, 
		const pelet::VariableClass& variable, pelet::ExpressionClass* expression, const UnicodeString& comment) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		UnicodeString scope;
		if (className.isEmpty() && methodName.isEmpty()) {
			scope = UNICODE_STRING_SIMPLE("<global>");
		}
		else if (className.isEmpty() && !methodName.isEmpty()) {
			scope = methodName;
		}
		else {
			scope = className + UNICODE_STRING_SIMPLE("::") + methodName;
		}
		UnicodeString type;
		
		if (variable.IsPhpDocVariable && !variable.PhpDocType.isEmpty()) {
			type += UNICODE_STRING_SIMPLE("Variable is decorated with a PHPDoc comment: ");
			type += variable.PhpDocType;
		}
		else if (pelet::ExpressionClass::ARRAY == expression->ExpressionType) {
			type = UNICODE_STRING_SIMPLE("Variable is an array");
		}
		else if (pelet::ExpressionClass::SCALAR == expression->ExpressionType) {
			type = UNICODE_STRING_SIMPLE("Variable is a primitive");
		}
		else if (pelet::ExpressionClass::VARIABLE == expression->ExpressionType) {
			type = UNICODE_STRING_SIMPLE("Variable is a variable expression. ");
			type += UNICODE_STRING_SIMPLE("Chain list is: ");
			pelet::VariableClass* srcVariable = (pelet::VariableClass*) expression;
			for (size_t i = 0; i < srcVariable->ChainList.size(); ++i) {
				if (srcVariable->ChainList[i].IsStatic && i > 0) {
					type += UNICODE_STRING_SIMPLE("::");
				}
				else if (i > 0) {
					type += UNICODE_STRING_SIMPLE("->");
				}
				type += srcVariable->ChainList[i].Name;
				if (srcVariable->ChainList[i].IsFunction) {
					type += UNICODE_STRING_SIMPLE("()");
				}
				if (i < (srcVariable->ChainList.size() - 1)) {
					type += UNICODE_STRING_SIMPLE(", ");
				}
			}
			
		}
		else if (pelet::ExpressionClass::UNKNOWN == expression->ExpressionType) {
			type = UNICODE_STRING_SIMPLE("Variable is of unknown type.");
		}
		
		u_fprintf(ufout, "Variable Found: %.*S in scope %S. %S\n", 
				variable.ChainList[0].Name.length(), variable.ChainList[0].Name.getBuffer(),
				scope.getTerminatedBuffer(),
				type.getTerminatedBuffer());
	}
Beispiel #8
0
	/**
	 * This method gets called when a trait method conflict has been resolved
	 * (an insteadof operation) 
	 *
	 * @param const UnicodeString& namespace the fully qualified namespace of the class that was found
	 * @param className name of the class that uses the trait
	 * @param traitUsedClassName the class name of the trait to be used
	 * @param traitMethodName name of the trait method that is to being resolved
	 * @param insteadOfList the list of fully qualified trait names that are listed after the insteadof operator
	 */
	virtual void TraitInsteadOfFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& traitUsedClassName,
		const UnicodeString& traitMethodName, const std::vector<UnicodeString>& insteadOfList) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Trait InsteadOf Found in class %.*S in namespace %.*S. Trait Class %.*S Trait Method %.*S \n", 
			className.length(), className.getBuffer(), 
			namespaceName.length(), namespaceName.getBuffer(),
			traitUsedClassName.length(), traitUsedClassName.getBuffer(),
			traitMethodName.length(), traitMethodName.getBuffer()
		);
		u_fprintf(ufout, "Instead of");
		for (size_t i = 0; i < insteadOfList.size(); ++i) {
			u_fprintf(ufout, " %.*S", insteadOfList[i].length(), insteadOfList[i].getBuffer());
		}
		u_fclose(ufout);
	}
Beispiel #9
0
	/**
	 * Override this method to perform custom logic when a trait method has been aliased
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the class that uses the trait
	 * @param traitUsedClassName the class name of the trait to be aliased
	 * @param traitMethodName the fully qualified name of the trait method that is to be aliased (hidden)
	 *        this may be empty if the trait adaptation only changes the visibility and
	 *        does not need to resolve a trait conflict
	 * @param alias the name of the new alias. alias may be empty when ONLY the visibility is changed.
	 * @param visibility the visbility of the trait method. may be PUBLIC if the visibility was not changed.
	 */
	virtual void TraitAliasFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& traitUsedClassName,
		const UnicodeString& traitMethodName, 
		const UnicodeString& alias, pelet::TokenClass::TokenIds visibility) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		if (!alias.isEmpty()) {
			const char* visibilityStr;
			if (pelet::TokenClass::PRIVATE == visibility) {
				visibilityStr = "private";
			}
			else if (pelet::TokenClass::PROTECTED == visibility) {
				visibilityStr = "protected";
			}
			else {
				visibilityStr = "public";
			}
			u_fprintf(ufout, "Trait Alias Found in class %.*S in namespace %.*S. Trait Class %.*S Trait Method %.*S Trait Alias %.*S New Visibility %s \n", 
				className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				traitUsedClassName.length(), traitUsedClassName.getBuffer(),
				traitMethodName.length(), traitMethodName.getBuffer(),
				alias.length(), alias.getBuffer(),
				visibilityStr
			);
		}
		else {
			const char* visibilityStr;
			if (pelet::TokenClass::PRIVATE == visibility) {
				visibilityStr = "private";
			}
			else if (pelet::TokenClass::PROTECTED == visibility) {
				visibilityStr = "protected";
			}
			else {
				visibilityStr = "public";
			}
			u_fprintf(ufout, "Trait Change in visbility Found in class %.*S in namespace %.*S. Trait Class %.*S Trait Method %.*S New Visibility %s\n", 
				className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				traitUsedClassName.length(), traitUsedClassName.getBuffer(),
				traitMethodName.length(), traitMethodName.getBuffer(),
				visibilityStr
			);
		}
		u_fclose(ufout);
	}
Beispiel #10
0
	/**
	 * This method gets called when a function is found.
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the function that was found
	 * @param const UnicodeString& functionName the name of the method that was found
	 * @param const UnicodeString& signature string containing method parameters.  String is normalized, meaning that
	 *        any extra white space is removed, and every token is separated by one space only. ie. for the code
	 *        "public function doWork( $item1,   $item2  ) " the signature will be  "($item1, $item2)"
	 * @param const UnicodeString& returnType the function's return type, as dictated by the PHPDoc comment
	 * @param const UnicodeString& comment PHPDoc attached to the class
	 * @param lineNumber the line number (1-based) that the function was found in
	 */
	virtual void FunctionFound(const UnicodeString& namespaceName, const UnicodeString& functionName, 
		const UnicodeString& signature, const UnicodeString& returnType, const UnicodeString& comment, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		if (returnType.isEmpty()) {
			u_fprintf(ufout, "Function Found: %.*S in namespace %.*S on line %d. Function Did not have @return in PHPDoc comment\n", 
				functionName.length(), functionName.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber);
		}
		else {
			u_fprintf(ufout, "Function Found: %.*S in namespace %.*S on line %d and it returns %.*S\n", 
				functionName.length(), functionName.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber,
				returnType.length(), returnType.getBuffer());
		}
		u_fclose(ufout);		
	}
Beispiel #11
0
	/* This method gets called when a class method is found.
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the class that was found
	 * @param const UnicodeString& className the name of the class that was found
	 * @param const UnicodeString& methodName the name of the method that was found
	 * @param const UnicodeString& signature string containing method parameters.  String is normalized, meaning that
	 *        any extra white space is removed, and every token is separated by one space only. ie. for the code
	 *        "public function doWork( $item1,   $item2  ) " the signature will be  "($item1, $item2)"
	 * @param const UnicodeString& returnType the method's return type, as dictated by the PHPDoc comment
	 * @param const UnicodeString& comment PHPDoc attached to the class
	 * @param visibility the visibility token attached to the method: PUBLIC, PROTECTED, or PRIVATE
	 * @param isStatic true if the method is static
	 * @param lineNumber the line number (1-based) that the method was found in
	 */
	virtual void MethodFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& methodName, 
		const UnicodeString& signature, const UnicodeString& returnType, const UnicodeString& comment, 
		pelet::TokenClass::TokenIds visibility, bool isStatic, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		if (returnType.isEmpty()) {
			u_fprintf(ufout, "Method Found: %.*S in class %.*S in namespace %.*S on line %d. Method did not have @return in PHPDoc comment\n", 
				methodName.length(), methodName.getBuffer(), className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber);
		}
		else {
			u_fprintf(ufout, "Method Found: %.*S in class %.*S in namespace %.*S on line %d and returns %.*S\n", 
				methodName.length(), methodName.getBuffer(), className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber,
				returnType.length(), returnType.getBuffer());
		}
		u_fclose(ufout);
	}
Beispiel #12
0
	/**
	 * Override this method to perform any custom logic when a class property is found.
	 * 
	 * @param const UnicodeString& namespace the fully qualified namespace of the class that was found
	 * @param const UnicodeString& className the name of the class that was found
	 * @param const UnicodeString& propertyName the name of the property that was found
	 * @param const UnicodeString& propertyType the property's type, as dictated by the PHPDoc comment
	 * @param const UnicodeString& comment PHPDoc attached to the property
	 * @param visibility the visibility token attached  to the property: PUBLIC, PROTECTED, or PRIVATE
	 * @param bool isConst true if property is a constant
	 * @param isStatic true if the property is static
	 * @param lineNumber the line number (1-based) that the property was found in
	 */
	virtual void PropertyFound(const UnicodeString& namespaceName, const UnicodeString& className, const UnicodeString& propertyName, 
		const UnicodeString& propertyType, const UnicodeString& comment, 
		pelet::TokenClass::TokenIds visibility, bool isConst, bool isStatic, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		if (propertyType.isEmpty()) {
			u_fprintf(ufout, "Property Found: %.*S in class %.*S in namespace %.*S on line %d. Did not have @return in PHPDoc comment\n", 
				propertyName.length(), propertyName.getBuffer(), className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber);
		}
		else {
			u_fprintf(ufout, "Property Found: %.*S in class %.*S in namespace %.*S on line %d and is of type %.*S\n", 
				propertyName.length(), propertyName.getBuffer(), className.length(), className.getBuffer(), 
				namespaceName.length(), namespaceName.getBuffer(),
				lineNumber,
				propertyType.length(), propertyType.getBuffer());
		}
		u_fclose(ufout);	
	}
Beispiel #13
0
/* Creating and using text boundaries */
int main( void )
{
	UErrorCode status = U_ZERO_ERROR;

	out = u_finit(stdout, NULL, NULL);

	u_fprintf(out, "ICU Iteration Sample Program (C++)\n\n");
    
	Test t;

	u_fprintf(out, "\n");
	u_fprintf(out, "Test::TestUCharIter()\n");

	t.TestUChariter();

	u_fprintf(out, "-----\n");
	u_fprintf(out, "Test::TestStringchariter()\n");

	t.TestStringiter();

	u_fprintf(out, "-----\n");

	return 0;
}
Beispiel #14
0
extern int
main(int argc, char* argv[]) {
    const char *encoding = NULL;
    const char *outputDir = NULL; /* NULL = no output directory, use current */
    const char *inputDir  = ".";
    int tostdout = 0;
    int prbom = 0;

    const char *pname;

    UResourceBundle *bundle = NULL;
    int32_t i = 0;

    const char* arg;

    /* Get the name of tool. */
    pname = uprv_strrchr(*argv, U_FILE_SEP_CHAR);
#if U_FILE_SEP_CHAR != U_FILE_ALT_SEP_CHAR
    if (!pname) {
        pname = uprv_strrchr(*argv, U_FILE_ALT_SEP_CHAR);
    }
#endif
    if (!pname) {
        pname = *argv;
    } else {
        ++pname;
    }

    /* error handling, printing usage message */
    argc=u_parseArgs(argc, argv, UPRV_LENGTHOF(options), options);

    /* error handling, printing usage message */
    if(argc<0) {
        fprintf(stderr,
            "%s: error in command line argument \"%s\"\n", pname,
            argv[-argc]);
    }
    if(argc<0 || options[0].doesOccur || options[1].doesOccur) {
        fprintf(argc < 0 ? stderr : stdout,
            "%csage: %s [ -h, -?, --help ] [ -V, --version ]\n"
            " [ -v, --verbose ] [ -e, --encoding encoding ] [ --bom ]\n"
            " [ -t, --truncate [ size ] ]\n"
            " [ -s, --sourcedir source ] [ -d, --destdir destination ]\n"
            " [ -i, --icudatadir directory ] [ -c, --to-stdout ]\n"
            " [ -A, --suppressAliases]\n"
            " bundle ...\n", argc < 0 ? 'u' : 'U',
            pname);
        return argc<0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR;
    }

    if(options[10].doesOccur) {
        fprintf(stderr,
                "%s version %s (ICU version %s).\n"
                "%s\n",
                pname, DERB_VERSION, U_ICU_VERSION, U_COPYRIGHT_STRING);
        return U_ZERO_ERROR;
    }
    if(options[2].doesOccur) {
        encoding = options[2].value;
    }

    if (options[3].doesOccur) {
      if(options[2].doesOccur) {
        fprintf(stderr, "%s: Error: don't specify an encoding (-e) when writing to stdout (-c).\n", pname);
        return 3;
      }
      tostdout = 1;
    }

    if(options[4].doesOccur) {
        opt_truncate = TRUE;
        if(options[4].value != NULL) {
            truncsize = atoi(options[4].value); /* user defined printable size */
        } else {
            truncsize = DERB_DEFAULT_TRUNC; /* we'll use default omitting size */
        }
    } else {
        opt_truncate = FALSE;
    }

    if(options[5].doesOccur) {
        verbose = TRUE;
    }

    if (options[6].doesOccur) {
        outputDir = options[6].value;
    }

    if(options[7].doesOccur) {
        inputDir = options[7].value; /* we'll use users resources */
    }

    if (options[8].doesOccur) {
        prbom = 1;
    }

    if (options[9].doesOccur) {
        u_setDataDirectory(options[9].value);
    }

    if (options[11].doesOccur) {
      suppressAliases = TRUE;
    }

    fflush(stderr); // use ustderr now.
    ustderr = u_finit(stderr, NULL, NULL);

    for (i = 1; i < argc; ++i) {
        static const UChar sp[] = { 0x0020 }; /* " " */

        arg = getLongPathname(argv[i]);

        if (verbose) {
          u_fprintf(ustderr, "processing bundle \"%s\"\n", argv[i]);
        }

        icu::CharString locale;
        UErrorCode status = U_ZERO_ERROR;
        {
            const char *p = findBasename(arg);
            const char *q = uprv_strrchr(p, '.');
            if (q == NULL) {
                locale.append(p, status);
            } else {
                locale.append(p, (int32_t)(q - p), status);
            }
        }
        if (U_FAILURE(status)) {
            return status;
        }

        icu::CharString infile;
        const char *thename = NULL;
        UBool fromICUData = !uprv_strcmp(inputDir, "-");
        if (!fromICUData) {
            UBool absfilename = *arg == U_FILE_SEP_CHAR;
#if U_PLATFORM_HAS_WIN32_API
            if (!absfilename) {
                absfilename = (uprv_strlen(arg) > 2 && isalpha(arg[0])
                    && arg[1] == ':' && arg[2] == U_FILE_SEP_CHAR);
            }
#endif
            if (absfilename) {
                thename = arg;
            } else {
                const char *q = uprv_strrchr(arg, U_FILE_SEP_CHAR);
#if U_FILE_SEP_CHAR != U_FILE_ALT_SEP_CHAR
                if (q == NULL) {
                    q = uprv_strrchr(arg, U_FILE_ALT_SEP_CHAR);
                }
#endif
                infile.append(inputDir, status);
                if(q != NULL) {
                    infile.appendPathPart(icu::StringPiece(arg, (int32_t)(q - arg)), status);
                }
                if (U_FAILURE(status)) {
                    return status;
                }
                thename = infile.data();
            }
        }
        if (thename) {
            bundle = ures_openDirect(thename, locale.data(), &status);
        } else {
            bundle = ures_open(fromICUData ? 0 : inputDir, locale.data(), &status);
        }
        if (U_SUCCESS(status)) {
            UFILE *out = NULL;

            const char *filename = 0;
            const char *ext = 0;

            if (locale.isEmpty() || !tostdout) {
                filename = findBasename(arg);
                ext = uprv_strrchr(filename, '.');
                if (!ext) {
                    ext = uprv_strchr(filename, 0);
                }
            }

            if (tostdout) {
                out = u_get_stdout();
            } else {
                icu::CharString thefile;
                if (outputDir) {
                    thefile.append(outputDir, status);
                }
                thefile.appendPathPart(filename, status);
                if (*ext) {
                    thefile.truncate(thefile.length() - (int32_t)uprv_strlen(ext));
                }
                thefile.append(".txt", status);
                if (U_FAILURE(status)) {
                    return status;
                }

                out = u_fopen(thefile.data(), "w", NULL, encoding);
                if (!out) {
                  u_fprintf(ustderr, "%s: couldn't create %s\n", pname, thefile.data());
                  u_fclose(ustderr);
                  return 4;
                }
            }

            // now, set the callback.
            ucnv_setFromUCallBack(u_fgetConverter(out), UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_C, 0, 0, &status);
            if (U_FAILURE(status)) {
              u_fprintf(ustderr, "%s: couldn't configure converter for encoding\n", pname);
              u_fclose(ustderr);
              if(!tostdout) {
                u_fclose(out);
              }
              return 3;
            }

            if (prbom) { /* XXX: Should be done only for UTFs */
              u_fputc(0xFEFF, out);
            }
            u_fprintf(out, "// -*- Coding: %s; -*-\n//\n", encoding ? encoding : getEncodingName(ucnv_getDefaultName()));
            u_fprintf(out, "// This file was dumped by derb(8) from ");
            if (thename) {
              u_fprintf(out, "%s", thename);
            } else if (fromICUData) {
              u_fprintf(out, "the ICU internal %s locale", locale.data());
            }

            u_fprintf(out, "\n// derb(8) by Vladimir Weinstein and Yves Arrouye\n\n");

            if (!locale.isEmpty()) {
              u_fprintf(out, "%s", locale.data());
            } else {
              u_fprintf(out, "%.*s%.*S", (int32_t)(ext - filename),  filename, UPRV_LENGTHOF(sp), sp);
            }
            printOutBundle(out, bundle, 0, pname, &status);

            if (!tostdout) {
                u_fclose(out);
            }
        }
        else {
            reportError(pname, &status, "opening resource file");
        }

        ures_close(bundle);
    }

    return 0;
}
bool pelet::UCharBufferedFileClass::OpenFile(FILE* file, int startingCapacity) {
	UFILE* uFile = u_finit(file, NULL, NULL);
	return OpenFile(uFile);
}
Beispiel #16
0
	/**
	 * Override this method to perform any custom logic when a namespace declaration is found.
	 * 
	 * @param const UnicodeString& namespaceName the name of the namespace name. Name will
	 *        be fully qualified (starts with '\')
	 * @param startingPos the character position (of the 'namespace' keyword in the original source code)
	 *         this is 0-based
	 */
	virtual void NamespaceDeclarationFound(const UnicodeString& namespaceName, int startingPos) { 
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Namespace Declaration Found: %.*S \n", namespaceName.length(), namespaceName.getBuffer());
		u_fclose(ufout);
	}
Beispiel #17
0
int main( void )
{
    UFILE *out;
    UErrorCode status  = U_ZERO_ERROR;
    out = u_finit(stdout, NULL, NULL);
    if(!out) {
        fprintf(stderr, "Could not initialize (finit()) over stdout! \n");
        return 1;
    }
    ucnv_setFromUCallBack(u_fgetConverter(out), UCNV_FROM_U_CALLBACK_ESCAPE,
                          NULL, NULL, NULL, &status);
    if(U_FAILURE(status)) {
        u_fprintf(out, "Warning- couldn't set the substitute callback - err %s\n", u_errorName(status));
    }

    /* End Demo boilerplate */

    u_fprintf(out,"ICU Case Mapping Sample Program\n\n");
    u_fprintf(out, "C++ Case Mapping\n\n");

    UnicodeString string("This is a test");
    /* lowercase = "istanbul" */
    UChar lowercase[] = {0x69, 0x73, 0x74, 0x61, 0x6e, 0x62, 0x75, 0x6c, 0};
    /* uppercase = "LATIN CAPITAL I WITH DOT ABOVE STANBUL" */
    UChar uppercase[] = {0x0130, 0x53, 0x54, 0x41, 0x4e, 0x42, 0x55, 0x4C, 0};

    UnicodeString upper(uppercase);
    UnicodeString lower(lowercase);

    u_fprintf(out, "\nstring: ");
    printUnicodeString(out, string);
    string.toUpper(); /* string = "THIS IS A TEST" */
    u_fprintf(out, "\ntoUpper(): ");
    printUnicodeString(out, string);
    string.toLower(); /* string = "this is a test" */
    u_fprintf(out, "\ntoLower(): ");
    printUnicodeString(out, string);

    u_fprintf(out, "\n\nlowercase=%S, uppercase=%S\n", lowercase, uppercase);


    string = upper;
    string.toLower(Locale("tr", "TR")); /* Turkish lower case map string =
                                        lowercase */
    u_fprintf(out, "\nupper.toLower: ");
    printUnicodeString(out, string);

    string = lower;
    string.toUpper(Locale("tr", "TR")); /* Turkish upper case map string =
                                        uppercase */
    u_fprintf(out, "\nlower.toUpper: ");
    printUnicodeString(out, string);


    u_fprintf(out, "\nEnd C++ sample\n\n");

    // Call the C version
    int rc = c_main(out);
    u_fclose(out);
    return rc;
}
Beispiel #18
0
	/**
	 * Override this method to perform any custom logic when an include / require / require_once / include_once declaration is found.
	 * 
	 * @param const UnicodeString& filename the name of the included file, but only if the statement
	 *        is a constant expression. Otherwise, lineNumber will be an empty string 
	 * @param lineNumber the line number (1-based) that the include/ was found in
	 */
	virtual void IncludeFound(const UnicodeString& filename, const int lineNumber) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Include or Require Found: %.*S on line %d\n", filename.length(), filename.getBuffer(), lineNumber);
		u_fclose(ufout);
	}
Beispiel #19
0
	/**
	 * Override this method to perform any custom logic when a namespace is imported ("use" keyword).
	 * 
	 * @param UnicodeString namespaceName the fully qualified namespace that is being imported. It will 
	 *        always begin with a leading slash, even if the original source did not include it
	 * @param alias any alias to the namespaceName. alias will never be empty. If the code does not
	 *        specify an alias, the alias will be the last part of the namespace.
	 *        For example the statement "use First\Class;" will result in the  alias being "Class"
	 * @param startingPos
	 *        Character position where the namespace use statement starts. This number is 
	 *        0-based. It is the position where the "use" token starts. For example,
	 *        in the statement "use \First\Child" then StartingPosition is the position of "use"
	 *        Even in the case of where a use statement has commas, then StartingPosition is the 
	 *        position of the namespace token. For example, in the statement
	 *        "use \First\Child, \Sec\Child" then StartingPosition for 
	 *        the namespace \Sec\Child is the position of "use"
	 * @see LexicalAnalyzerClass::GetCharacterPosition()
	 */	
	virtual void NamespaceUseFound(const UnicodeString& namespaceName, const UnicodeString& alias, int startingPos) {
		UFILE* ufout = u_finit(stdout, NULL, NULL);
		u_fprintf(ufout, "Namespace Import (Use) Found: %.*S alias %d\n", namespaceName.length(), namespaceName.getBuffer(), 
			alias.length(), alias.getBuffer());
		u_fclose(ufout);
	}
Beispiel #20
0
/*
 *  main()   This one function is all of the application code.
 */
int main(int argc, char **argv)
{
    UBool              displayUsage  = FALSE;    /* Set true if command line err or help      */
                                                 /*   option was requested.                   */
    UBool              verbose       = FALSE;    /* Set true if -v command line option.       */
    char              *optionError   = NULL;     /* If command line contains an unrecognized  */
                                                 /*   option, this will point to it.          */
    char              *locale=NULL;              /* Locale name.  Null for system default,    */
                                                 /*   otherwise set from command line.        */
    const char *       programName   = argv[0];  /* Program invocation name.                  */


    UFILE             *u_stdout;                 /* Unicode stdout file.                      */
    UErrorCode         err           = U_ZERO_ERROR;   /* Error return, used for most ICU     */
                                                       /*   functions.                        */

    UResourceBundle   *myResources;              /* ICU Resource "handles"                    */
    UResourceBundle   *fortunes_r;

    int32_t            numFortunes;              /* Number of fortune strings available.      */
    int                i;

    const UChar       *resString;                /* Points to strings fetched from Resources. */
    int32_t            len;


    /*  Process command line options.
     *     -l  locale          specify a locale
     *     -v                  verbose mode.  Display extra messages.
     *     -? or --help        display a usage line
     */
    for (i=1; i<argc; i++) {
        if (strcmp(argv[i], "-l") ==0) {
            if (++i < argc) {
                locale = argv[i];
            }
            continue;
        }
        if (strcmp(argv[i], "-v") == 0) {
            verbose = TRUE;
            continue;}
        if (strcmp(argv[i], "-?") == 0 ||
            strcmp(argv[i], "--help") == 0) {
            displayUsage = TRUE;
            continue;}
        optionError = argv[i];
        displayUsage = TRUE;
        break;
    }

    /* ICU's icuio package provides a convenient way to write Unicode
     *    data to stdout.  The string data that we get from resources
     *    will be UChar * strings, which icuio can handle nicely.
     */
    u_stdout = u_finit(stdout, NULL /*locale*/,  NULL /*codepage */);
    if (verbose) {
        u_fprintf(u_stdout, "%s:  checking output via icuio.\n", programName);
    }

#ifndef UFORTUNE_NOSETAPPDATA
    /* Tell ICU where our resource data is located in memory.
     *   The data lives in the Fortune_Resources dll, and we just
     *   pass the address of an exported symbol from that library
     *   to ICU.
     */
    udata_setAppData("fortune_resources", &fortune_resources_dat, &err);
    if (U_FAILURE(err)) {
        fprintf(stderr, "%s: udata_setAppData failed with error \"%s\"\n", programName, u_errorName(err));
        exit(-1);
    }
#endif

    /* Open our resources.
    */
    myResources = ures_open("fortune_resources", locale, &err);
    if (U_FAILURE(err)) {
        fprintf(stderr, "%s: ures_open failed with error \"%s\"\n", programName, u_errorName(err));
        exit(-1);
    }
    if (verbose) {
        u_fprintf(u_stdout, "status from ures_open(\"fortune_resources\", %s) is %s\n",
            locale? locale: " ", u_errorName(err));
    }

    /*
     * Display any command line option usage errors and/or the
     *     usage help message.  These messages come from our resource bundle.
     */
    if (optionError != NULL) {
        const UChar *msg = ures_getStringByKey(myResources, "optionMessage", &len, &err);
        if (U_FAILURE(err)) {
            fprintf(stderr, "%s: ures_getStringByKey(\"optionMessage\") failed, %s\n",
                programName, u_errorName(err));
            exit(-1);
        }
        u_file_write(msg,  len, u_stdout);              /* msg is UChar *, from resource    */
        u_fprintf(u_stdout, " %s\n", optionError);      /* optionError is char *, from argv */
    }

    if (displayUsage) {
        const UChar *usage;
        int          returnValue=0;

        usage = ures_getStringByKey(myResources, "usage", &len, &err);
        if (U_FAILURE(err)) {
            fprintf(stderr, "%s: ures_getStringByKey(\"usage\") failed, %s\n", programName, u_errorName(err));
            exit(-1);
        }
        u_file_write(usage,  len, u_stdout);
        if (optionError != NULL) {returnValue = -1;}
        return returnValue;
    }

    /*
     * Open the "fortunes" resources from within the already open resources
     */
    fortunes_r = ures_getByKey(myResources, "fortunes", NULL, &err);
    if (U_FAILURE(err)) {
        fprintf(stderr, "%s: ures_getByKey(\"fortunes\") failed, %s\n", programName, u_errorName(err));
        exit(-1);
    }


    /*
     * Pick up and display a random fortune
     *
     */
    numFortunes = ures_countArrayItems(myResources, "fortunes", &err);
    if (U_FAILURE(err)) {
        fprintf(stderr, "%s: ures_countArrayItems(\"fortunes\") failed, %s\n", programName, u_errorName(err));
        exit(-1);
    }
    if (numFortunes <= 0) {
        fprintf(stderr, "%s: no fortunes found.\n", programName);
        exit(-1);
    }

    i = (int)time(NULL) % numFortunes;    /*  Use time to pick a somewhat-random fortune.  */
    resString = ures_getStringByIndex(fortunes_r, i, &len, &err);
    if (U_FAILURE(err)) {
        fprintf(stderr, "%s: ures_getStringByIndex(%d) failed, %s\n", programName, i, u_errorName(err));
        exit(-1);
    }

    u_file_write(resString, len, u_stdout);      /* Write out the message           */
	u_fputc(0x0a, u_stdout);                     /*   and a trailing newline	    */

    return 0;
}
Beispiel #21
0
extern int
main(int argc, char* argv[]) {

    UResourceBundle *bundle = NULL;
    UErrorCode status = U_ZERO_ERROR;
    UFILE *out = NULL;
    int32_t i = 0;
    const char* arg;
    char resPathBuffer[1024];
#ifdef WIN32
    currdir = _getcwd(NULL, 0);
#else
    currdir = getcwd(NULL, 0);
#endif

    argc=u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options);

    /* error handling, printing usage message */
    if(argc<0) {
        fprintf(stderr,
            "error in command line argument \"%s\"\n",
            argv[-argc]);
    }
    if(argc<2 || options[0].doesOccur || options[1].doesOccur) {
        fprintf(stderr,
            "usage: %s [-options] locale(s)\n",
            argv[0]);
        return argc<0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR;
    }

    if(options[2].doesOccur) {
        locale = options[2].value;
    } else {
        locale = 0;
    }

    if(options[3].doesOccur) {
        encoding = options[3].value;
    } else {
        encoding = NULL;
    }

    if(options[4].doesOccur) {
        if(options[4].value != NULL) {
            resPath = options[4].value; /* we'll use users resources */
        } else {
            resPath = NULL; /* we'll use ICU system resources for dumping */
        }
    } else {
        strcpy(resPathBuffer, currdir);
        /*strcat(resPathBuffer, U_FILE_SEP_STRING);
        strcat(resPathBuffer, "uresb");*/
        resPath = resPathBuffer; /* we'll just dump uresb samples resources */
    }

    if(options[5].doesOccur) {
        trunc = TRUE;
        if(options[5].value != NULL) {
            truncsize = atoi(options[5].value); /* user defined printable size */
        } else {
            truncsize = URESB_DEFAULTTRUNC; /* we'll use default omitting size */
        }
    } else {
        trunc = FALSE;
    }

    if(options[6].doesOccur) {
        VERBOSE = TRUE;
    }

    outerr = u_finit(stderr, locale, encoding);
    out = u_finit(stdout, locale, encoding); 

    for(i = 1; i < argc; ++i) {
        status = U_ZERO_ERROR;
        arg = getLongPathname(argv[i]);

        u_fprintf(out, "uresb: processing file \"%s\" in path \"%s\"\n", arg, resPath);
        bundle = ures_open(resPath, arg, &status);
        if(U_SUCCESS(status)) {
            u_fprintf(out, "%s\n", arg);
            printOutBundle(out, bundle, 0, &status);
        } else {
            reportError(&status);
        }

        ures_close(bundle);
    }



    u_fclose(out);
    u_fclose(outerr);
    return 0;
}
Beispiel #22
0
UBreakIterator* 
get_rules(const char *ruleFileName, UErrorCode status) 
{
    /*  Read in the rule source file */
    long        result;
    long        ruleFileSize;
    FILE        *file;
    OFILE       *ufile;
    UBreakIterator *return_me;

    file = fopen(ruleFileName, "rb");
    if( file == 0 ) {
        fprintf(stderr, "Could not open file \"%s\"\n", ruleFileName);
        exit(-1);
    }
    fseek(file, 0, SEEK_END);
    ruleFileSize = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    char *ruleBufferC = (char *) omalloc (ruleFileSize + 1);
    ruleBufferC[ruleFileSize] = '\0';
    result = (long)fread(ruleBufferC, 1, ruleFileSize, file);
    if (result != ruleFileSize)  {
        fprintf(stderr, "Error reading file \"%s\"\n", ruleFileName);
        exit (-1);
    }
    
    /* Look for a Unicode Signature (BOM) on the rule file */
    int32_t        signatureLength;
    const char *   ruleSourceC = ruleBufferC;
    const char*    encoding = ucnv_detectUnicodeSignature(
                           ruleSourceC, ruleFileSize, &signatureLength, &status);
    /* fprintf(stderr, "DetectUnicodeSig: \"%s\"\n", encoding); */
    if (U_FAILURE(status)) 
    {
        fprintf(stderr, "\nCan not initialize ICU.  status = %s\n",
            u_errorName(status));
        exit(1);
    }
    if(encoding!=NULL )
    {
        ruleSourceC  += signatureLength;
        ruleFileSize -= signatureLength;
    }
    /* fprintf(stderr, "encoding: \"%s\"\n", encoding); */

    /* Open a converter to take the rule file to UTF-16 */
    UConverter* conv;
    conv = ucnv_open(encoding, &status);
    if (U_FAILURE(status)) {
        fprintf(stderr, "ucnv_open: ICU Error \"%s\"\n", u_errorName(status));
        exit(1);
    }

    ufile = u_finit(file, NULL, NULL);
    u_frewind(ufile);
    UChar *ruleSourceU = (UChar *) omalloc ((ruleFileSize*sizeof(UChar))+1);
    long charsRead = u_file_read(ruleSourceU, ruleFileSize, ufile);
    /* u_fprintf(u_stderr, "Chars read: \"%i\", File size: \"%i\"\n", charsRead, ruleFileSize); */
    ruleSourceU[charsRead] = 0;
    /* u_fprintf(u_stderr, "RulesourceU POST: \"%S\"\n", ruleSourceU); */
    ucnv_close(conv);
    u_fclose(ufile);

    /*  Create the break iterator from the rules */
    /*     This will compile the rules. */
    UParseError parseError;
    parseError.line = 0;
    parseError.offset = 0;
    return_me = ubrk_openRules(ruleSourceU, ruleFileSize, NULL, 0, &parseError, &status);
    if (U_FAILURE(status)) {
        fprintf(stderr, "createRuleBasedBreakIterator: ICU Error \"%s\"  at line %d, column %d\n",
                u_errorName(status), (int)parseError.line, (int)parseError.offset);
        exit(1);
    };

    return return_me;
}
Beispiel #23
0
int main(void)
{
    int ret;
    int32_t l, u;
    UErrorCode status;
    UFILE *ustdout, *ustderr;
    URegularExpression *uregex;
    UBool case_insensitive = FALSE;
    UParseError pe = {-1, -1, {0}, {0}};
    UChar pattern[] = {
        0x0028, // 28, (
        0x005C, // 5C, backslash
        0x0070, // 70, p
        0x007B, // 7B, {
        0x004C, // 4C, L
        0x007D, // 7D, }
        0x0029, // 29, )
        0x0028, // 28, (
        0x005C, // 5C, backslash
        0x0070, // 70, p
        0x007B, // 7B, {
        0x004E, // 4E, N
        0x0064, // 64, d
        0x007D, // 7D, }
        0x0029, // 29, )
        0
    };
    UChar string[] = {
        0xD835, 0xDE3C, // A
        0xD835, 0xDE3C, // A
        0xD835, 0xDFE2, // 0
        0xD835, 0xDE3D, // B
        0xD835, 0xDE3D, // B
        0xD835, 0xDFE3, // 1
        0xD835, 0xDE3E, // C
        0xD835, 0xDE3E, // C
        0xD835, 0xDFE4, // 2
        0
    };

    uregex = NULL;
    ret = EXIT_SUCCESS;
    status = U_ZERO_ERROR;
    ustdout = u_finit(stdout, NULL, NULL);
    ustderr = u_finit(stderr, NULL, NULL);

    uregex = uregex_open(pattern, -1, case_insensitive ? UREGEX_CASE_INSENSITIVE : 0, &pe, &status);
    if (U_FAILURE(status)) {
        if (U_REGEX_RULE_SYNTAX == status) {
            u_fprintf(ustderr, "Invalid pattern: error at offset %d\n\t%S\n\t%*c\n", pe.offset, pattern, pe.offset, '^');
        }
        goto end;
    }
    uregex_setText(uregex, string, -1, &status);
    if (U_FAILURE(status)) {
        goto end;
    }
    while (uregex_findNext(uregex, &status)) {
        l = uregex_start(uregex, 0, &status);
        if (U_FAILURE(status)) {
            goto end;
        }
        u = uregex_end(uregex, 0, &status);
        if (U_FAILURE(status)) {
            goto end;
        }
        // $0
        u_fprintf(ustdout, "Match found at %d position (to %d): %.*S\n", l, u, u - l, string + l);
        // $1 à $2 (on pourrait aussi utiliser uregex_group avec un groupNum à valeur 0 pour récupérer $0)
        {
            UChar buffer[1024];
            int32_t i, l, g;

            l = uregex_groupCount(uregex, &status);
            if (U_FAILURE(status)) {
                icu_error(status, "uregex_groupCount");
            }
            for (i = 1; i <= l; i++) {
                g = uregex_group(uregex, i, buffer, USTRING_SIZE(buffer), &status);
                if (U_FAILURE(status)) {
                    icu_error(status, "uregex_group");
                }
                u_fprintf(ustdout, "$%d : %S\n", i, buffer);
            }
        }
    }
    if (U_FAILURE(status)) {
        goto end;
    }

    if (FALSE) {
end:
        ret = EXIT_FAILURE;
    }
    if (NULL != ustderr) {
        u_fclose(ustderr);
    }
    if (NULL != ustdout) {
        u_fclose(ustdout);
    }
    if (NULL != uregex) {
        uregex_close(uregex);
    }
    u_cleanup();

    return ret;
}