1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include <cmath> // For isfinite.
8 #include "src/builtins.h"
9 #include "src/code-stubs.h"
10 #include "src/contexts.h"
11 #include "src/conversions.h"
12 #include "src/hashmap.h"
13 #include "src/parser.h"
14 #include "src/property.h"
15 #include "src/property-details.h"
16 #include "src/scopes.h"
17 #include "src/string-stream.h"
18 #include "src/type-info.h"
23 // ----------------------------------------------------------------------------
24 // All the Accept member functions for each syntax tree node type.
26 #define DECL_ACCEPT(type) \
27 void type::Accept(AstVisitor* v) { v->Visit##type(this); }
28 AST_NODE_LIST(DECL_ACCEPT)
32 // ----------------------------------------------------------------------------
33 // Implementation of other node functionality.
36 bool Expression::IsSmiLiteral() const {
37 return IsLiteral() && AsLiteral()->value()->IsSmi();
41 bool Expression::IsStringLiteral() const {
42 return IsLiteral() && AsLiteral()->value()->IsString();
46 bool Expression::IsNullLiteral() const {
47 return IsLiteral() && AsLiteral()->value()->IsNull();
51 bool Expression::IsUndefinedLiteral(Isolate* isolate) const {
52 const VariableProxy* var_proxy = AsVariableProxy();
53 if (var_proxy == NULL) return false;
54 Variable* var = var_proxy->var();
55 // The global identifier "undefined" is immutable. Everything
56 // else could be reassigned.
57 return var != NULL && var->location() == Variable::UNALLOCATED &&
58 var_proxy->raw_name()->IsOneByteEqualTo("undefined");
62 VariableProxy::VariableProxy(Zone* zone, Variable* var, int position)
63 : Expression(zone, position),
64 bit_field_(IsThisField::encode(var->is_this()) |
65 IsAssignedField::encode(false) |
66 IsResolvedField::encode(false)),
67 variable_feedback_slot_(FeedbackVectorICSlot::Invalid()),
68 raw_name_(var->raw_name()) {
73 VariableProxy::VariableProxy(Zone* zone, const AstRawString* name, bool is_this,
75 : Expression(zone, position),
76 bit_field_(IsThisField::encode(is_this) | IsAssignedField::encode(false) |
77 IsResolvedField::encode(false)),
78 variable_feedback_slot_(FeedbackVectorICSlot::Invalid()),
82 void VariableProxy::BindTo(Variable* var) {
83 DCHECK((is_this() && var->is_this()) || raw_name() == var->raw_name());
90 Assignment::Assignment(Zone* zone, Token::Value op, Expression* target,
91 Expression* value, int pos)
92 : Expression(zone, pos),
93 bit_field_(IsUninitializedField::encode(false) |
94 KeyTypeField::encode(ELEMENT) |
95 StoreModeField::encode(STANDARD_STORE) |
96 TokenField::encode(op)),
99 binary_operation_(NULL) {}
102 Token::Value Assignment::binary_op() const {
104 case Token::ASSIGN_BIT_OR: return Token::BIT_OR;
105 case Token::ASSIGN_BIT_XOR: return Token::BIT_XOR;
106 case Token::ASSIGN_BIT_AND: return Token::BIT_AND;
107 case Token::ASSIGN_SHL: return Token::SHL;
108 case Token::ASSIGN_SAR: return Token::SAR;
109 case Token::ASSIGN_SHR: return Token::SHR;
110 case Token::ASSIGN_ADD: return Token::ADD;
111 case Token::ASSIGN_SUB: return Token::SUB;
112 case Token::ASSIGN_MUL: return Token::MUL;
113 case Token::ASSIGN_DIV: return Token::DIV;
114 case Token::ASSIGN_MOD: return Token::MOD;
115 default: UNREACHABLE();
117 return Token::ILLEGAL;
121 bool FunctionLiteral::AllowsLazyCompilation() {
122 return scope()->AllowsLazyCompilation();
126 bool FunctionLiteral::AllowsLazyCompilationWithoutContext() {
127 return scope()->AllowsLazyCompilationWithoutContext();
131 int FunctionLiteral::start_position() const {
132 return scope()->start_position();
136 int FunctionLiteral::end_position() const {
137 return scope()->end_position();
141 LanguageMode FunctionLiteral::language_mode() const {
142 return scope()->language_mode();
146 bool FunctionLiteral::uses_super_property() const {
147 DCHECK_NOT_NULL(scope());
148 return scope()->uses_super_property() || scope()->inner_uses_super_property();
152 // Helper to find an existing shared function info in the baseline code for the
153 // given function literal. Used to canonicalize SharedFunctionInfo objects.
154 void FunctionLiteral::InitializeSharedInfo(
155 Handle<Code> unoptimized_code) {
156 for (RelocIterator it(*unoptimized_code); !it.done(); it.next()) {
157 RelocInfo* rinfo = it.rinfo();
158 if (rinfo->rmode() != RelocInfo::EMBEDDED_OBJECT) continue;
159 Object* obj = rinfo->target_object();
160 if (obj->IsSharedFunctionInfo()) {
161 SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
162 if (shared->start_position() == start_position()) {
163 shared_info_ = Handle<SharedFunctionInfo>(shared);
171 ObjectLiteralProperty::ObjectLiteralProperty(Expression* key, Expression* value,
172 Kind kind, bool is_static,
173 bool is_computed_name)
178 is_static_(is_static),
179 is_computed_name_(is_computed_name) {}
182 ObjectLiteralProperty::ObjectLiteralProperty(AstValueFactory* ast_value_factory,
183 Expression* key, Expression* value,
185 bool is_computed_name)
189 is_static_(is_static),
190 is_computed_name_(is_computed_name) {
191 if (!is_computed_name &&
192 key->AsLiteral()->raw_value()->EqualsString(
193 ast_value_factory->proto_string())) {
195 } else if (value_->AsMaterializedLiteral() != NULL) {
196 kind_ = MATERIALIZED_LITERAL;
197 } else if (value_->IsLiteral()) {
205 bool ObjectLiteral::Property::IsCompileTimeValue() {
206 return kind_ == CONSTANT ||
207 (kind_ == MATERIALIZED_LITERAL &&
208 CompileTimeValue::IsCompileTimeValue(value_));
212 void ObjectLiteral::Property::set_emit_store(bool emit_store) {
213 emit_store_ = emit_store;
217 bool ObjectLiteral::Property::emit_store() {
222 void ObjectLiteral::CalculateEmitStore(Zone* zone) {
223 const auto GETTER = ObjectLiteral::Property::GETTER;
224 const auto SETTER = ObjectLiteral::Property::SETTER;
226 ZoneAllocationPolicy allocator(zone);
228 ZoneHashMap table(Literal::Match, ZoneHashMap::kDefaultHashMapCapacity,
230 for (int i = properties()->length() - 1; i >= 0; i--) {
231 ObjectLiteral::Property* property = properties()->at(i);
232 if (property->is_computed_name()) continue;
233 if (property->kind() == ObjectLiteral::Property::PROTOTYPE) continue;
234 Literal* literal = property->key()->AsLiteral();
235 DCHECK(!literal->value()->IsNull());
237 // If there is an existing entry do not emit a store unless the previous
238 // entry was also an accessor.
239 uint32_t hash = literal->Hash();
240 ZoneHashMap::Entry* entry = table.Lookup(literal, hash, true, allocator);
241 if (entry->value != NULL) {
243 static_cast<ObjectLiteral::Property*>(entry->value)->kind();
244 if (!((property->kind() == GETTER && previous_kind == SETTER) ||
245 (property->kind() == SETTER && previous_kind == GETTER))) {
246 property->set_emit_store(false);
249 entry->value = property;
254 bool ObjectLiteral::IsBoilerplateProperty(ObjectLiteral::Property* property) {
255 return property != NULL &&
256 property->kind() != ObjectLiteral::Property::PROTOTYPE;
260 void ObjectLiteral::BuildConstantProperties(Isolate* isolate) {
261 if (!constant_properties_.is_null()) return;
263 // Allocate a fixed array to hold all the constant properties.
264 Handle<FixedArray> constant_properties = isolate->factory()->NewFixedArray(
265 boilerplate_properties_ * 2, TENURED);
268 // Accumulate the value in local variables and store it at the end.
269 bool is_simple = true;
271 uint32_t max_element_index = 0;
272 uint32_t elements = 0;
273 for (int i = 0; i < properties()->length(); i++) {
274 ObjectLiteral::Property* property = properties()->at(i);
275 if (!IsBoilerplateProperty(property)) {
280 if (position == boilerplate_properties_ * 2) {
281 DCHECK(property->is_computed_name());
284 DCHECK(!property->is_computed_name());
286 MaterializedLiteral* m_literal = property->value()->AsMaterializedLiteral();
287 if (m_literal != NULL) {
288 m_literal->BuildConstants(isolate);
289 if (m_literal->depth() >= depth_acc) depth_acc = m_literal->depth() + 1;
292 // Add CONSTANT and COMPUTED properties to boilerplate. Use undefined
293 // value for COMPUTED properties, the real value is filled in at
294 // runtime. The enumeration order is maintained.
295 Handle<Object> key = property->key()->AsLiteral()->value();
296 Handle<Object> value = GetBoilerplateValue(property->value(), isolate);
298 // Ensure objects that may, at any point in time, contain fields with double
299 // representation are always treated as nested objects. This is true for
300 // computed fields (value is undefined), and smi and double literals
301 // (value->IsNumber()).
302 // TODO(verwaest): Remove once we can store them inline.
303 if (FLAG_track_double_fields &&
304 (value->IsNumber() || value->IsUninitialized())) {
305 may_store_doubles_ = true;
308 is_simple = is_simple && !value->IsUninitialized();
310 // Keep track of the number of elements in the object literal and
311 // the largest element index. If the largest element index is
312 // much larger than the number of elements, creating an object
313 // literal with fast elements will be a waste of space.
314 uint32_t element_index = 0;
316 && Handle<String>::cast(key)->AsArrayIndex(&element_index)
317 && element_index > max_element_index) {
318 max_element_index = element_index;
320 } else if (key->IsSmi()) {
321 int key_value = Smi::cast(*key)->value();
323 && static_cast<uint32_t>(key_value) > max_element_index) {
324 max_element_index = key_value;
329 // Add name, value pair to the fixed array.
330 constant_properties->set(position++, *key);
331 constant_properties->set(position++, *value);
334 constant_properties_ = constant_properties;
336 (max_element_index <= 32) || ((2 * elements) >= max_element_index);
337 has_elements_ = elements > 0;
338 set_is_simple(is_simple);
339 set_depth(depth_acc);
343 void ArrayLiteral::BuildConstantElements(Isolate* isolate) {
344 if (!constant_elements_.is_null()) return;
346 // Allocate a fixed array to hold all the object literals.
347 Handle<JSArray> array =
348 isolate->factory()->NewJSArray(0, FAST_HOLEY_SMI_ELEMENTS);
349 JSArray::Expand(array, values()->length());
351 // Fill in the literals.
352 bool is_simple = true;
354 bool is_holey = false;
355 for (int i = 0, n = values()->length(); i < n; i++) {
356 Expression* element = values()->at(i);
357 MaterializedLiteral* m_literal = element->AsMaterializedLiteral();
358 if (m_literal != NULL) {
359 m_literal->BuildConstants(isolate);
360 if (m_literal->depth() + 1 > depth_acc) {
361 depth_acc = m_literal->depth() + 1;
364 Handle<Object> boilerplate_value = GetBoilerplateValue(element, isolate);
365 if (boilerplate_value->IsTheHole()) {
367 } else if (boilerplate_value->IsUninitialized()) {
369 JSObject::SetOwnElement(
370 array, i, handle(Smi::FromInt(0), isolate), SLOPPY).Assert();
372 JSObject::SetOwnElement(array, i, boilerplate_value, SLOPPY).Assert();
376 Handle<FixedArrayBase> element_values(array->elements());
378 // Simple and shallow arrays can be lazily copied, we transform the
379 // elements array to a copy-on-write array.
380 if (is_simple && depth_acc == 1 && values()->length() > 0 &&
381 array->HasFastSmiOrObjectElements()) {
382 element_values->set_map(isolate->heap()->fixed_cow_array_map());
385 // Remember both the literal's constant values as well as the ElementsKind
386 // in a 2-element FixedArray.
387 Handle<FixedArray> literals = isolate->factory()->NewFixedArray(2, TENURED);
389 ElementsKind kind = array->GetElementsKind();
390 kind = is_holey ? GetHoleyElementsKind(kind) : GetPackedElementsKind(kind);
392 literals->set(0, Smi::FromInt(kind));
393 literals->set(1, *element_values);
395 constant_elements_ = literals;
396 set_is_simple(is_simple);
397 set_depth(depth_acc);
401 Handle<Object> MaterializedLiteral::GetBoilerplateValue(Expression* expression,
403 if (expression->IsLiteral()) {
404 return expression->AsLiteral()->value();
406 if (CompileTimeValue::IsCompileTimeValue(expression)) {
407 return CompileTimeValue::GetValue(isolate, expression);
409 return isolate->factory()->uninitialized_value();
413 void MaterializedLiteral::BuildConstants(Isolate* isolate) {
414 if (IsArrayLiteral()) {
415 return AsArrayLiteral()->BuildConstantElements(isolate);
417 if (IsObjectLiteral()) {
418 return AsObjectLiteral()->BuildConstantProperties(isolate);
420 DCHECK(IsRegExpLiteral());
421 DCHECK(depth() >= 1); // Depth should be initialized.
425 void UnaryOperation::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
426 // TODO(olivf) If this Operation is used in a test context, then the
427 // expression has a ToBoolean stub and we want to collect the type
428 // information. However the GraphBuilder expects it to be on the instruction
429 // corresponding to the TestContext, therefore we have to store it here and
430 // not on the operand.
431 set_to_boolean_types(oracle->ToBooleanTypes(expression()->test_id()));
435 void BinaryOperation::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
436 // TODO(olivf) If this Operation is used in a test context, then the right
437 // hand side has a ToBoolean stub and we want to collect the type information.
438 // However the GraphBuilder expects it to be on the instruction corresponding
439 // to the TestContext, therefore we have to store it here and not on the
440 // right hand operand.
441 set_to_boolean_types(oracle->ToBooleanTypes(right()->test_id()));
445 static bool IsTypeof(Expression* expr) {
446 UnaryOperation* maybe_unary = expr->AsUnaryOperation();
447 return maybe_unary != NULL && maybe_unary->op() == Token::TYPEOF;
451 // Check for the pattern: typeof <expression> equals <string literal>.
452 static bool MatchLiteralCompareTypeof(Expression* left,
456 Handle<String>* check) {
457 if (IsTypeof(left) && right->IsStringLiteral() && Token::IsEqualityOp(op)) {
458 *expr = left->AsUnaryOperation()->expression();
459 *check = Handle<String>::cast(right->AsLiteral()->value());
466 bool CompareOperation::IsLiteralCompareTypeof(Expression** expr,
467 Handle<String>* check) {
468 return MatchLiteralCompareTypeof(left_, op_, right_, expr, check) ||
469 MatchLiteralCompareTypeof(right_, op_, left_, expr, check);
473 static bool IsVoidOfLiteral(Expression* expr) {
474 UnaryOperation* maybe_unary = expr->AsUnaryOperation();
475 return maybe_unary != NULL &&
476 maybe_unary->op() == Token::VOID &&
477 maybe_unary->expression()->IsLiteral();
481 // Check for the pattern: void <literal> equals <expression> or
482 // undefined equals <expression>
483 static bool MatchLiteralCompareUndefined(Expression* left,
488 if (IsVoidOfLiteral(left) && Token::IsEqualityOp(op)) {
492 if (left->IsUndefinedLiteral(isolate) && Token::IsEqualityOp(op)) {
500 bool CompareOperation::IsLiteralCompareUndefined(
501 Expression** expr, Isolate* isolate) {
502 return MatchLiteralCompareUndefined(left_, op_, right_, expr, isolate) ||
503 MatchLiteralCompareUndefined(right_, op_, left_, expr, isolate);
507 // Check for the pattern: null equals <expression>
508 static bool MatchLiteralCompareNull(Expression* left,
512 if (left->IsNullLiteral() && Token::IsEqualityOp(op)) {
520 bool CompareOperation::IsLiteralCompareNull(Expression** expr) {
521 return MatchLiteralCompareNull(left_, op_, right_, expr) ||
522 MatchLiteralCompareNull(right_, op_, left_, expr);
526 // ----------------------------------------------------------------------------
529 bool Declaration::IsInlineable() const {
530 return proxy()->var()->IsStackAllocated();
533 bool FunctionDeclaration::IsInlineable() const {
538 // ----------------------------------------------------------------------------
539 // Recording of type feedback
541 // TODO(rossberg): all RecordTypeFeedback functions should disappear
542 // once we use the common type field in the AST consistently.
544 void Expression::RecordToBooleanTypeFeedback(TypeFeedbackOracle* oracle) {
545 set_to_boolean_types(oracle->ToBooleanTypes(test_id()));
549 bool Call::IsUsingCallFeedbackICSlot(Isolate* isolate) const {
550 CallType call_type = GetCallType(isolate);
551 if (IsUsingCallFeedbackSlot(isolate) || call_type == POSSIBLY_EVAL_CALL) {
558 bool Call::IsUsingCallFeedbackSlot(Isolate* isolate) const {
559 // SuperConstructorCall uses a CallConstructStub, which wants
560 // a Slot, not an IC slot.
561 return GetCallType(isolate) == SUPER_CALL;
565 FeedbackVectorRequirements Call::ComputeFeedbackRequirements(Isolate* isolate) {
566 int ic_slots = IsUsingCallFeedbackICSlot(isolate) ? 1 : 0;
567 int slots = IsUsingCallFeedbackSlot(isolate) ? 1 : 0;
568 // A Call uses either a slot or an IC slot.
569 DCHECK((ic_slots & slots) == 0);
570 return FeedbackVectorRequirements(slots, ic_slots);
574 Call::CallType Call::GetCallType(Isolate* isolate) const {
575 VariableProxy* proxy = expression()->AsVariableProxy();
577 if (proxy->var()->is_possibly_eval(isolate)) {
578 return POSSIBLY_EVAL_CALL;
579 } else if (proxy->var()->IsUnallocated()) {
581 } else if (proxy->var()->IsLookupSlot()) {
582 return LOOKUP_SLOT_CALL;
586 if (expression()->AsSuperReference() != NULL) return SUPER_CALL;
588 Property* property = expression()->AsProperty();
589 return property != NULL ? PROPERTY_CALL : OTHER_CALL;
593 bool Call::ComputeGlobalTarget(Handle<GlobalObject> global,
594 LookupIterator* it) {
595 target_ = Handle<JSFunction>::null();
596 cell_ = Handle<Cell>::null();
597 DCHECK(it->IsFound() && it->GetHolder<JSObject>().is_identical_to(global));
598 cell_ = it->GetPropertyCell();
599 if (cell_->value()->IsJSFunction()) {
600 Handle<JSFunction> candidate(JSFunction::cast(cell_->value()));
601 // If the function is in new space we assume it's more likely to
602 // change and thus prefer the general IC code.
603 if (!it->isolate()->heap()->InNewSpace(*candidate)) {
612 void CallNew::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
613 FeedbackVectorSlot allocation_site_feedback_slot =
614 FLAG_pretenuring_call_new ? AllocationSiteFeedbackSlot()
615 : CallNewFeedbackSlot();
617 oracle->GetCallNewAllocationSite(allocation_site_feedback_slot);
618 is_monomorphic_ = oracle->CallNewIsMonomorphic(CallNewFeedbackSlot());
619 if (is_monomorphic_) {
620 target_ = oracle->GetCallNewTarget(CallNewFeedbackSlot());
625 void ObjectLiteral::Property::RecordTypeFeedback(TypeFeedbackOracle* oracle) {
626 DCHECK(!is_computed_name());
627 TypeFeedbackId id = key()->AsLiteral()->LiteralFeedbackId();
629 oracle->CollectReceiverTypes(id, &maps);
630 receiver_type_ = maps.length() == 1 ? maps.at(0)
631 : Handle<Map>::null();
635 // ----------------------------------------------------------------------------
636 // Implementation of AstVisitor
638 void AstVisitor::VisitDeclarations(ZoneList<Declaration*>* declarations) {
639 for (int i = 0; i < declarations->length(); i++) {
640 Visit(declarations->at(i));
645 void AstVisitor::VisitStatements(ZoneList<Statement*>* statements) {
646 for (int i = 0; i < statements->length(); i++) {
647 Statement* stmt = statements->at(i);
649 if (stmt->IsJump()) break;
654 void AstVisitor::VisitExpressions(ZoneList<Expression*>* expressions) {
655 for (int i = 0; i < expressions->length(); i++) {
656 // The variable statement visiting code may pass NULL expressions
657 // to this code. Maybe this should be handled by introducing an
658 // undefined expression or literal? Revisit this code if this
660 Expression* expression = expressions->at(i);
661 if (expression != NULL) Visit(expression);
666 // ----------------------------------------------------------------------------
667 // Regular expressions
669 #define MAKE_ACCEPT(Name) \
670 void* RegExp##Name::Accept(RegExpVisitor* visitor, void* data) { \
671 return visitor->Visit##Name(this, data); \
673 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_ACCEPT)
676 #define MAKE_TYPE_CASE(Name) \
677 RegExp##Name* RegExpTree::As##Name() { \
680 bool RegExpTree::Is##Name() { return false; }
681 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
682 #undef MAKE_TYPE_CASE
684 #define MAKE_TYPE_CASE(Name) \
685 RegExp##Name* RegExp##Name::As##Name() { \
688 bool RegExp##Name::Is##Name() { return true; }
689 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_TYPE_CASE)
690 #undef MAKE_TYPE_CASE
693 static Interval ListCaptureRegisters(ZoneList<RegExpTree*>* children) {
694 Interval result = Interval::Empty();
695 for (int i = 0; i < children->length(); i++)
696 result = result.Union(children->at(i)->CaptureRegisters());
701 Interval RegExpAlternative::CaptureRegisters() {
702 return ListCaptureRegisters(nodes());
706 Interval RegExpDisjunction::CaptureRegisters() {
707 return ListCaptureRegisters(alternatives());
711 Interval RegExpLookahead::CaptureRegisters() {
712 return body()->CaptureRegisters();
716 Interval RegExpCapture::CaptureRegisters() {
717 Interval self(StartRegister(index()), EndRegister(index()));
718 return self.Union(body()->CaptureRegisters());
722 Interval RegExpQuantifier::CaptureRegisters() {
723 return body()->CaptureRegisters();
727 bool RegExpAssertion::IsAnchoredAtStart() {
728 return assertion_type() == RegExpAssertion::START_OF_INPUT;
732 bool RegExpAssertion::IsAnchoredAtEnd() {
733 return assertion_type() == RegExpAssertion::END_OF_INPUT;
737 bool RegExpAlternative::IsAnchoredAtStart() {
738 ZoneList<RegExpTree*>* nodes = this->nodes();
739 for (int i = 0; i < nodes->length(); i++) {
740 RegExpTree* node = nodes->at(i);
741 if (node->IsAnchoredAtStart()) { return true; }
742 if (node->max_match() > 0) { return false; }
748 bool RegExpAlternative::IsAnchoredAtEnd() {
749 ZoneList<RegExpTree*>* nodes = this->nodes();
750 for (int i = nodes->length() - 1; i >= 0; i--) {
751 RegExpTree* node = nodes->at(i);
752 if (node->IsAnchoredAtEnd()) { return true; }
753 if (node->max_match() > 0) { return false; }
759 bool RegExpDisjunction::IsAnchoredAtStart() {
760 ZoneList<RegExpTree*>* alternatives = this->alternatives();
761 for (int i = 0; i < alternatives->length(); i++) {
762 if (!alternatives->at(i)->IsAnchoredAtStart())
769 bool RegExpDisjunction::IsAnchoredAtEnd() {
770 ZoneList<RegExpTree*>* alternatives = this->alternatives();
771 for (int i = 0; i < alternatives->length(); i++) {
772 if (!alternatives->at(i)->IsAnchoredAtEnd())
779 bool RegExpLookahead::IsAnchoredAtStart() {
780 return is_positive() && body()->IsAnchoredAtStart();
784 bool RegExpCapture::IsAnchoredAtStart() {
785 return body()->IsAnchoredAtStart();
789 bool RegExpCapture::IsAnchoredAtEnd() {
790 return body()->IsAnchoredAtEnd();
794 // Convert regular expression trees to a simple sexp representation.
795 // This representation should be different from the input grammar
796 // in as many cases as possible, to make it more difficult for incorrect
797 // parses to look as correct ones which is likely if the input and
798 // output formats are alike.
799 class RegExpUnparser FINAL : public RegExpVisitor {
801 RegExpUnparser(std::ostream& os, Zone* zone) : os_(os), zone_(zone) {}
802 void VisitCharacterRange(CharacterRange that);
803 #define MAKE_CASE(Name) virtual void* Visit##Name(RegExp##Name*, \
804 void* data) OVERRIDE;
805 FOR_EACH_REG_EXP_TREE_TYPE(MAKE_CASE)
813 void* RegExpUnparser::VisitDisjunction(RegExpDisjunction* that, void* data) {
815 for (int i = 0; i < that->alternatives()->length(); i++) {
817 that->alternatives()->at(i)->Accept(this, data);
824 void* RegExpUnparser::VisitAlternative(RegExpAlternative* that, void* data) {
826 for (int i = 0; i < that->nodes()->length(); i++) {
828 that->nodes()->at(i)->Accept(this, data);
835 void RegExpUnparser::VisitCharacterRange(CharacterRange that) {
836 os_ << AsUC16(that.from());
837 if (!that.IsSingleton()) {
838 os_ << "-" << AsUC16(that.to());
844 void* RegExpUnparser::VisitCharacterClass(RegExpCharacterClass* that,
846 if (that->is_negated()) os_ << "^";
848 for (int i = 0; i < that->ranges(zone_)->length(); i++) {
849 if (i > 0) os_ << " ";
850 VisitCharacterRange(that->ranges(zone_)->at(i));
857 void* RegExpUnparser::VisitAssertion(RegExpAssertion* that, void* data) {
858 switch (that->assertion_type()) {
859 case RegExpAssertion::START_OF_INPUT:
862 case RegExpAssertion::END_OF_INPUT:
865 case RegExpAssertion::START_OF_LINE:
868 case RegExpAssertion::END_OF_LINE:
871 case RegExpAssertion::BOUNDARY:
874 case RegExpAssertion::NON_BOUNDARY:
882 void* RegExpUnparser::VisitAtom(RegExpAtom* that, void* data) {
884 Vector<const uc16> chardata = that->data();
885 for (int i = 0; i < chardata.length(); i++) {
886 os_ << AsUC16(chardata[i]);
893 void* RegExpUnparser::VisitText(RegExpText* that, void* data) {
894 if (that->elements()->length() == 1) {
895 that->elements()->at(0).tree()->Accept(this, data);
898 for (int i = 0; i < that->elements()->length(); i++) {
900 that->elements()->at(i).tree()->Accept(this, data);
908 void* RegExpUnparser::VisitQuantifier(RegExpQuantifier* that, void* data) {
909 os_ << "(# " << that->min() << " ";
910 if (that->max() == RegExpTree::kInfinity) {
913 os_ << that->max() << " ";
915 os_ << (that->is_greedy() ? "g " : that->is_possessive() ? "p " : "n ");
916 that->body()->Accept(this, data);
922 void* RegExpUnparser::VisitCapture(RegExpCapture* that, void* data) {
924 that->body()->Accept(this, data);
930 void* RegExpUnparser::VisitLookahead(RegExpLookahead* that, void* data) {
931 os_ << "(-> " << (that->is_positive() ? "+ " : "- ");
932 that->body()->Accept(this, data);
938 void* RegExpUnparser::VisitBackReference(RegExpBackReference* that,
940 os_ << "(<- " << that->index() << ")";
945 void* RegExpUnparser::VisitEmpty(RegExpEmpty* that, void* data) {
951 std::ostream& RegExpTree::Print(std::ostream& os, Zone* zone) { // NOLINT
952 RegExpUnparser unparser(os, zone);
953 Accept(&unparser, NULL);
958 RegExpDisjunction::RegExpDisjunction(ZoneList<RegExpTree*>* alternatives)
959 : alternatives_(alternatives) {
960 DCHECK(alternatives->length() > 1);
961 RegExpTree* first_alternative = alternatives->at(0);
962 min_match_ = first_alternative->min_match();
963 max_match_ = first_alternative->max_match();
964 for (int i = 1; i < alternatives->length(); i++) {
965 RegExpTree* alternative = alternatives->at(i);
966 min_match_ = Min(min_match_, alternative->min_match());
967 max_match_ = Max(max_match_, alternative->max_match());
972 static int IncreaseBy(int previous, int increase) {
973 if (RegExpTree::kInfinity - previous < increase) {
974 return RegExpTree::kInfinity;
976 return previous + increase;
980 RegExpAlternative::RegExpAlternative(ZoneList<RegExpTree*>* nodes)
982 DCHECK(nodes->length() > 1);
985 for (int i = 0; i < nodes->length(); i++) {
986 RegExpTree* node = nodes->at(i);
987 int node_min_match = node->min_match();
988 min_match_ = IncreaseBy(min_match_, node_min_match);
989 int node_max_match = node->max_match();
990 max_match_ = IncreaseBy(max_match_, node_max_match);
995 CaseClause::CaseClause(Zone* zone, Expression* label,
996 ZoneList<Statement*>* statements, int pos)
997 : Expression(zone, pos),
999 statements_(statements),
1000 compare_type_(Type::None(zone)) {}
1003 uint32_t Literal::Hash() {
1004 return raw_value()->IsString()
1005 ? raw_value()->AsString()->hash()
1006 : ComputeLongHash(double_to_uint64(raw_value()->AsNumber()));
1011 bool Literal::Match(void* literal1, void* literal2) {
1012 const AstValue* x = static_cast<Literal*>(literal1)->raw_value();
1013 const AstValue* y = static_cast<Literal*>(literal2)->raw_value();
1014 return (x->IsString() && y->IsString() && *x->AsString() == *y->AsString()) ||
1015 (x->IsNumber() && y->IsNumber() && x->AsNumber() == y->AsNumber());
1019 } } // namespace v8::internal